问题描述
我有 2 个数组,我试图仅从它们获取唯一值.所以我不只是想删除重复项,我实际上是在尝试删除两个重复项.
I have 2 arrays that I'm trying to get the unique values only from them. So I'm not just trying to remove duplicates, I'm actually trying to remove both duplicates.
所以如果我得到这样的 2 个数组:
So if I'm getting the 2 arrays like this:
$array1 = array();
$array2 = array();
foreach($values1 as $value1){ //output: $array1 = 10, 15, 20, 25;
$array1[] = $value1;
}
foreach($values2 as $value2){ //output: $array2 = 10, 15, 100, 150;
$array2[] = $value2;
}
我正在寻找的最终输出是
The final output I'm looking for is
$output = 20, 25, 100, 150;
有什么巧妙的方法来完成这项工作吗?
Any neat way to getting this done?
推荐答案
其他答案都在正确的轨道上,但是 array_diff
仅适用于一个方向——即.它返回存在于第一个数组中但不存在于任何其他数组中的值.
The other answers are on the right track, but array_diff
only works in one direction -- ie. it returns the values that exist in the first array given that aren't in any others.
您要做的是获取两个方向的差异,然后将差异合并在一起:
What you want to do is get the difference in both directions and then merge the differences together:
$array1 = array(10, 15, 20, 25);
$array2 = array(10, 15, 100, 150);
$output = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
// $output will be (20, 25, 100, 150);
这篇关于从 2 个数组中获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!