php 与 array_intersect 相对?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5582242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:52:42  来源:igfitidea点击:

Opposite of array_intersect?

phparraysarray-intersect

提问by Itay Moav -Malimovka

Is there a built-in function to get all members of array 1 which do not exist in array 2?
I know how to do it programatically, only wondering if there is a built-in function that does the same. So please, no code examples.

是否有内置函数来获取数组 1 中不存在于数组 2 中的所有成员?
我知道如何以编程方式做到这一点,只是想知道是否有一个内置函数可以做到这一点。所以拜托,没有代码示例。

回答by Jon

That sounds like a job for array_diff.

这听起来像是array_diff.

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

返回一个数组,其中包含 array1 中不存在于任何其他数组中的所有条目。

回答by Dallas Caley

array_diff is definitely the obvious choice but it is not technically the opposite of array interesect. Take this example:

array_diff 绝对是显而易见的选择,但它在技术上并不是数组 interesect 的对立面。拿这个例子:

$arr1 = array('rabbit','cat','dog');

$arr2 = array('cat','dog','bird');

print_r( array_diff($arr1, $arr2) );

What you want is a result with 'rabbit' and 'bird' in it but what you get is only rabbit because it is looking for what is in the first array but not the second (and not vice versa). to truly get the result you want you must do something like this:

您想要的是包含 'rabbit' 和 'bird' 的结果,但您得到的只是 rabbit ,因为它正在寻找第一个数组中的内容而不是第二个数组(反之亦然)。要真正获得您想要的结果,您必须执行以下操作:

$arr1 = array('rabbit','cat','dog');

$arr2 = array('cat','dog','bird');

$diff1 = array_diff($arr1, $arr2);
$diff2 = array_diff($arr2, $arr1);
print_r( array_merge($diff1, $diff2) );

Note: This method will only work on arrays with numeric keys.

注意:此方法仅适用于带有数字键的数组。

回答by KingCrunch

$diff = array_diff($array1, $array2);

array_diff()

数组差异()

回答by Jesse

I found this docstore.mik.ua/orelly/webprog/pcook/ch04_24.htmquite useful.

我发现这个docstore.mik.ua/orelly/webprog/pcook/ch04_24.htm非常有用。

You might want a reverse diff, by reversing the order of the arrays in a standard diff.

您可能需要反向差异,通过反转标准差异中的数组顺序。

回答by Khel_MVA

Just to clarify as I was looking into this question the answers of @Jon and @Dallas Caley are both correct depending on the domain of your arrays.

只是为了澄清在我研究这个问题时@Jon 和@Dallas Caley 的答案都是正确的,具体取决于您的数组域。

If the array against what you are comparing is the full domain of your results then a simple array_diff will suffice as per @Jon answer.

如果与您比较的数组是结果的完整域,那么根据@Jon 的回答,一个简单的 array_diff 就足够了。

If the array against what you are comparing is NOT the full domain of your results then you should go with the double array_diff as per @Dallas Caley answer.

如果与您比较的数组不是结果的完整域,那么您应该按照@Dallas Caley 的回答使用双 array_diff。