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代码>作为...价值?
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'),
);
您必须遍历所有项目,分析值
,并取消设置正确的项目:
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屋!