两个数组之间的差异我有两个数组。我想要这两个数组之间的区别。也就是说,如何找到两个数组中不存在的值? $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);
3 回答
![?](http://img1.sycdn.imooc.com/54584cfb0001308402200220-100-100.jpg)
慕村9548890
TA贡献1884条经验 获得超4个赞
注意:这个答案将返回$ array2中$ array1中不存在的值,它不会返回$ array1中不在$ array2中的值。
$diff = array_diff($array2, $array1);
![?](http://img1.sycdn.imooc.com/5458478b0001f01502200220-100-100.jpg)
慕婉清6462132
TA贡献1804条经验 获得超2个赞
如果要以递归方式获取数组之间的差异,请尝试以下函数:
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);
- 3 回答
- 0 关注
- 698 浏览
添加回答
举报
0/150
提交
取消