简体   繁体   English

PHP比较两个数组

[英]PHP Compare two arrays

Say I have two arrays: 说我有两个数组:

     $a = a,b,c;
     $b = a,b;

When I compare this array output should be c . 当我比较这个数组输出应该是c

Omit the common values in both array. 省略两个数组中的公共值。

The quick answer: 快速回答:

array_merge(array_diff($a, $b), array_diff($b, $a));

array-diff($a, $b) will only extract values from $a which are not in $b. array-diff($ a,$ b)只会从$ a中提取不在$ b中的值。

The idea is to merge the differences. 这个想法是合并差异。

And another way to achieve your goal might be: 另一种实现目标的方法可能是:

function array_unique_merge() {
        return array_unique(call_user_func_array('array_merge', func_get_args()));
    }

Have a look at the PHP array_diff function. 看看PHP array_diff函数。

$a = a,b,c;
$b = a,b;
$c = array_diff($a,$b);

Firstly, that's not valid PHP - but... 首先,这不是有效的PHP - 但是......

$a = array("a","b","c");
$b = array("a","b");
print_r(array_diff($a,$b)); // Array ( [2] => c )

Just to make things more straighforward 只是为了让事情变得更加直截了当

$a = array("a","b","c");
$b = array("a","b");
$new_array = array_merge(array_diff($a, $b), array_diff($b, $a));
while (list ($key, $val) = each ($new_array)) {
echo $val;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM