PHP从关联数组中删除元素 [英] PHP Remove elements from associative array
问题描述
我有一个看起来像这样的PHP数组:
I have an PHP array that looks something like this:
Index Key Value
[0] 1 Awaiting for Confirmation
[1] 2 Assigned
[2] 3 In Progress
[3] 4 Completed
[4] 5 Mark As Spam
当我var_dump数组值时,我得到以下信息:
When I var_dump the array values i get this:
array(5) { [0]=> array(2) { ["key"]=> string(1) "1" ["value"]=> string(25) "Awaiting for Confirmation" } [1]=> array(2) { ["key"]=> string(1) "2" ["value"]=> string(9) "Assigned" } [2]=> array(2) { ["key"]=> string(1) "3" ["value"]=> string(11) "In Progress" } [3]=> array(2) { ["key"]=> string(1) "4" ["value"]=> string(9) "Completed" } [4]=> array(2) { ["key"]=> string(1) "5" ["value"]=> string(12) "Mark As Spam" } }
我想删除已完成和标记为垃圾邮件.我知道我可以unset[$array[3],$array[4])
,但是问题是有时索引号可能会不同.
I wanted to remove Completed and Mark As Spam. I know I can unset[$array[3],$array[4])
, but the problem is that sometimes the index number can be different.
是否可以通过匹配值名称而不是键值来删除它们?
Is there a way to remove them by matching the value name instead of the key value?
推荐答案
您的数组很奇怪:为什么不只是将key
用作索引,而将value
用作...值呢? /strong>
Your array is quite strange : why not just use the key
as index, and the value
as... the value ?
如果这样声明数组,会不会容易得多:
Wouldn't it be a lot easier if your array was declared like this :
$array = array(
1 => 'Awaiting for Confirmation',
2 => 'Asssigned',
3 => 'In Progress',
4 => 'Completed',
5 => 'Mark As Spam',
);
这将允许您将key
的值用作访问数组的索引...
That would allow you to use your values of key
as indexes to access the array...
您将能够使用函数来搜索值,例如 array_search()
:
And you'd be able to use functions to search on the values, such as array_search()
:
$indexCompleted = array_search('Completed', $array);
unset($array[$indexCompleted]);
$indexSpam = array_search('Mark As Spam', $array);
unset($array[$indexSpam]);
var_dump($array);
比使用阵列更容易,不是吗?
Easier than with your array, no ?
相反,您的数组如下所示:
Instead, with your array that looks like this :
$array = array(
array('key' => 1, 'value' => 'Awaiting for Confirmation'),
array('key' => 2, 'value' => 'Asssigned'),
array('key' => 3, 'value' => 'In Progress'),
array('key' => 4, 'value' => 'Completed'),
array('key' => 5, 'value' => 'Mark As Spam'),
);
您必须遍历所有项目,以分析value
,并取消设置正确的项目:
You'll have to loop over all items, to analyse the value
, and unset the right items :
foreach ($array as $index => $data) {
if ($data['value'] == 'Completed' || $data['value'] == 'Mark As Spam') {
unset($array[$index]);
}
}
var_dump($array);
即使可行,也不是那么简单...而且我坚持:您不能更改数组的格式,以使用更简单的键/值系统吗?
Even if do-able, it's not that simple... and I insist : can you not change the format of your array, to work with a simpler key/value system ?
这篇关于PHP从关联数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!