简体   繁体   English

PHP数组diff仅在键上递归(多维)

[英]PHP array diff recursively (multidimensional) only on the keys

I want to extract an array_diff comparing the structure and the keys of two multidimensional arrays. 我想提取一个array_diff来比较两个多维数组的结构和键。

Example: 例:

<?php
$array_1 =
['abc'=> '',
    'def'=> ['', '', [
        'ijk' => '']
    ]
];

$array_2 =
['abc'=> '',
    'def'=> ['', '', [
        'ijK' => '']
    ]
];

I would like an array diff of this telling me that the key 'ijK' is not the same name that 'ijk' (or not present on the first array). 我想要一个这样的数组diff告诉我,键'ijK'与'ijk'(或第一个数组中不存在)的名称不同。

only the keys are important to me..the values are always empty. 只有键才对我很重要......值总是空的。

function array_key_recursive_compare($array1, $array2) {
    $diff = false;
        // Left-to-right
        foreach ($array1 as $key => $value) {
            if (!array_key_exists($key,$array2)) {
                $diff[0][$key] = $value;
            } elseif (is_array($value)) {
                if (!is_array($array2[$key])) {
                    $diff[0][$key] = $value;
                    $diff[1][$key] = $array2[$key];
                } else {
                    $new = array_compare($value, $array2[$key]);
                    if ($new !== false) {
                        if (isset($new[0]))
                            $diff[0][$key] = $new[0];
                        if (isset($new[1]))
                            $diff[1][$key] = $new[1];
                    };
                };
            } elseif ($array2[$key] !== $value) {
                $diff[0][$key] = $value;
                $diff[1][$key] = $array2[$key];
            };
        };
        // Right-to-left
        foreach ($array2 as $key => $value) {
            if (!array_key_exists($key,$array1)) {
                $diff[1][$key] = $value;
            }
            // No direct comparison because matching keys were compared in the
            // left-to-right loop earlier, recursively.
        }
        return $diff;
    }

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

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