两个数组之间的差异

use*_*695 34 php

我有两个数组.我想要这两个数组之间的区别.也就是说,如何找到两个数组中不存在的值?

 $array1=Array ( [0] => 64 [1] => 98 [2] => 112 [3] => 92 [4] => 92 [5] => 92 ) ;
 $array2=Array ( [0] => 3 [1] => 26 [2] => 38 [3] => 40 [4] => 44 [5] => 46 [6] => 48 [7] => 52 [8] => 64 [9] => 68 [10] => 70 [11] => 72 [12] => 102 [13] => 104 [14] => 106 [15] => 92 [16] => 94 [17] => 96 [18] => 98 [19] => 100 [20] => 108 [21] => 110 [22] => 112);
Run Code Online (Sandbox Code Playgroud)

Cra*_*der 159

要获得两个阵列之间的差异,您需要执行以下操作:

$fullDiff = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
Run Code Online (Sandbox Code Playgroud)

原因在于,它array_diff()只会为您提供$array1但不是$array2,而不是相反的值.以上将给你们两个.

  • 如果您需要维护密钥:`$ full_diff = array_diff($ array1,$ array2)+ array_diff($ array2,$ array1);` (2认同)

Kin*_*nch 41

注意:这个答案将返回$ array2中$ array1中不存在的值,它不会返回$ array1中不在$ array2中的值.

$diff = array_diff($array2, $array1);
Run Code Online (Sandbox Code Playgroud)

$array2

  • 这似乎是不正确的 - 它不会返回`$ array2`中不存在的`$ array2`中的值.[Crasherspeeder](http://stackoverflow.com/questions/10077840/difference-between-two-arrays/10077920#10077920)似乎没错. (17认同)
  • @Crasherspeeder是正确的,这是一个单向检查 - 提问者想要两者. (10认同)

Mo *_*ami 5

如果要以递归方式获取数组之间的差异,请尝试以下函数:

function arrayDiffRecursive($firstArray, $secondArray, $reverseKey = false)
{
    $oldKey = 'old';
    $newKey = 'new';
    if ($reverseKey) {
        $oldKey = 'new';
        $newKey = 'old';
    }
    $difference = [];
    foreach ($firstArray as $firstKey => $firstValue) {
        if (is_array($firstValue)) {
            if (!array_key_exists($firstKey, $secondArray) || !is_array($secondArray[$firstKey])) {
                $difference[$oldKey][$firstKey] = $firstValue;
                $difference[$newKey][$firstKey] = '';
            } else {
                $newDiff = arrayDiffRecursive($firstValue, $secondArray[$firstKey], $reverseKey);
                if (!empty($newDiff)) {
                    $difference[$oldKey][$firstKey] = $newDiff[$oldKey];
                    $difference[$newKey][$firstKey] = $newDiff[$newKey];
                }
            }
        } else {
            if (!array_key_exists($firstKey, $secondArray) || $secondArray[$firstKey] != $firstValue) {
                $difference[$oldKey][$firstKey] = $firstValue;
                $difference[$newKey][$firstKey] = $secondArray[$firstKey];
            }
        }
    }
    return $difference;
}
Run Code Online (Sandbox Code Playgroud)

测试:

$differences = array_replace_recursive(
    arrayDiffRecursive($firstArray, $secondArray),
    arrayDiffRecursive($secondArray, $firstArray, true)
);
var_dump($differences);
Run Code Online (Sandbox Code Playgroud)