为了账号安全,请及时绑定邮箱和手机立即绑定

两个数组之间的差异

两个数组之间的差异

PHP
郎朗坤 2019-07-27 14:23:13
两个数组之间的差异我有两个数组。我想要这两个数组之间的区别。也就是说,如何找到两个数组中不存在的值? $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 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

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

$diff = array_diff($array2, $array1);

array_diff()


查看完整回答
反对 回复 2019-07-27
?
慕婉清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);


查看完整回答
反对 回复 2019-07-27
  • 3 回答
  • 0 关注
  • 698 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信