问题描述
我有一个像这样的数组:[312, 401, 1599, 3]
I have an array like : [312, 401, 1599, 3]
使用array_diff( [312, 401, 1599, 3], [401] )
我可以删除一个值,在我的示例中,我删除了值401.
With array_diff( [312, 401, 1599, 3], [401] )
I can remove a value, in my example I removed the value 401.
但是如果我有这个[312,401,401,401,1599,3],怎么能只删除一次值401?
But if I have this : [312, 401, 401, 401, 1599, 3], how can remove just one time the value 401 ?
删除第一个或最后一个值并不重要,我只需要删除一个401值,如果要删除所有401值,则必须删除三遍.
It is not important if I remove the first or last value, I just need to remove ONE 401 value, and if I want to remove all 401 values, I have to remove three times.
谢谢!
推荐答案
使用array_search
可以获取给定值的 first 匹配键,然后可以使用unset
删除它.
With array_search
you can get the first matching key of the given value, then you can delete it with unset
.
if (false !== $key = array_search(401, $array)) {
unset($array[$key]);
}
这篇关于PHP从数组中删除特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!