从数组,如果它存在于一个“不允许的词”数组中删除项目 [英] Remove item from array if it exists in a 'disallowed words' array

查看:138
本文介绍了从数组,如果它存在于一个“不允许的词”数组中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

Array
(
    [0] => tom
    [1] => and
    [2] => jerry
)

和我也有一个不允许的话数组:

And I also have a disallowed words array:

Array
(
    [0] => and
    [1] => foo
    [2] => bar
)

我需要做的是,也出现在第二个数组中的第一个数组中删除任何项目,在这种情况下,例如,1键将需要删除,如'和'是不允许的话阵列中的

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.

现在我现在有这个code,它确实在禁止字的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]);
    }
}

现在我知道这code很烂,我想知道的是,如果有一个从它存在于另一个阵列,尤其是如果它否定了使用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.

非常感谢,

Many thanks, Ben

推荐答案

您想 和array_diff

和array_diff 返回包含数组
  所有从数组1 是项
  在任何其他的不是present
  数组。

array_diff returns an array containing all the entries from array1 that are not present in any of the other arrays.

所以,你想是这样的:

$good = array_diff($arr, $disallowed_words);

这篇关于从数组,如果它存在于一个“不允许的词”数组中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆