如果项目存在于“不允许的词"数组中,则从数组中删除它 [英] Remove item from array if it exists in a 'disallowed words' array
问题描述
我有一个数组:
Array
(
[0] => tom
[1] => and
[2] => jerry
)
而且我还有一个不允许使用的字词数组:
And I also have a disallowed words array:
Array
(
[0] => and
[1] => foo
[2] => bar
)
我需要做的是删除也出现在第二个数组中的第一个数组中的任何项目,例如,在本例中,需要删除键 1,因为and"在不允许的单词数组中.
What I need to do is remove any item in the first array that also appears in the second array, in this instance for example, key 1 would need to be removed, as 'and' is in the disallowed words array.
现在我有这个代码,它对不允许的词执行 foreach,然后使用 array_search 查找任何匹配项:
Now I currently have this code, which does a foreach on the disallowed words and then uses array_search to find any matches:
$arr=array('tom','and','jerry');
$disallowed_words=array('and','or','if');
foreach($disallowed_words as $key => $value) {
$arr_key=array_search($value,$array);
if($arr_key!='') {
unset($search_terms[$arr_key]);
}
}
现在我知道这段代码很烂,我想知道是否有一种更有效的方法可以从另一个数组中存在的数组中删除一个项目,特别是如果它使用 foreach 进行否定.
Now I know this code sucks, what I want to know is if there is a more efficient method of removing and item from an array where it exists in another array, especially if it negates using a foreach.
非常感谢,本
推荐答案
你想要 array_diff
.
array_diff
返回一个包含array1
中的所有条目不存在于任何其他数组.
array_diff
returns an array containing all the entries fromarray1
that are not present in any of the other arrays.
所以你想要这样的东西:
So you want something like:
$good = array_diff($arr, $disallowed_words);
这篇关于如果项目存在于“不允许的词"数组中,则从数组中删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!