两个数组之间的差异

两个数组之间的差异

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

 $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);


郎朗坤
浏览 699回答 3
3回答

慕村9548890

注意:这个答案将返回$ array2中$ array1中不存在的值,它不会返回$ array1中不在$ array2中的值。$diff = array_diff($array2, $array1);array_diff()

慕婉清6462132

如果要以递归方式获取数组之间的差异,请尝试以下函数: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;}测试:$differences = array_replace_recursive(     arrayDiffRecursive($firstArray, $secondArray),     arrayDiffRecursive($secondArray, $firstArray, true));var_dump($differences);
打开App,查看更多内容
随时随地看视频慕课网APP