PHP数组按值删除(不是键)

本文翻译自:PHP array delete by value (not key)

I have a PHP array as follows: 我有一个PHP数组,如下所示:

$messages = [312, 401, 1599, 3, ...];

I want to delete the element containing the value $del_val (for example, $del_val=401 ), but I don't know its key. 我想删除包含值$del_val的元素(例如$del_val=401 ),但是我不知道它的键。 This might help: each value can only be there once . 这可能会有所帮助: 每个值只能存在一次

I'm looking for the simplest function to perform this task, please. 我正在寻找执行此任务的最简单功能。


#1楼

参考:https://stackoom.com/question/UJZO/PHP数组按值删除-不是键


#2楼

Well, deleting an element from array is basically just set difference with one element. 好吧,从数组中删除一个元素基本上只是与一个元素设置不同

array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]

It generalizes nicely, you can remove as many elements as you like at the same time, if you want. 概括性很好,如果需要,您可以同时删除任意多个元素。

Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. 免责声明:请注意,我的解决方案会生成一个数组的新副本,同时保持旧副本不变,这与接受的变异答案相反。 Pick the one you need. 选择您需要的那个。


#3楼

$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);

#4楼

One interesting way is by using array_keys() : 一种有趣的方法是使用array_keys()

foreach (array_keys($messages, 401, true) as $key) {
    unset($messages[$key]);
}

The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (ie using === for comparison). array_keys()函数使用两个附加参数,仅返回特定值的键以及是否需要严格检查(即,使用===进行比较)。

This can also remove multiple array items with the same value (eg [1, 2, 3, 3, 4] ). 这也可以删除具有相同值的多个数组项(例如[1, 2, 3, 3, 4] )。


#5楼

Have a look at following code: 看下面的代码:

$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');

You can do: 你可以做:

$arr = array_diff($arr, array('remove_me', 'remove_me_also'));

And that will get you this array: 这将为您提供以下数组:

array('nice_item', 'another_liked_item')

#6楼

To delete multiple values try this one: 要删除多个值,请尝试以下一项:

while (($key = array_search($del_val, $messages)) !== false) 
{
    unset($messages[$key]);
}
发布了0 篇原创文章 · 获赞 137 · 访问量 84万+

猜你喜欢

转载自blog.csdn.net/xfxf996/article/details/105385725