如何在php中的两个多维数组之间进行数组diff

时间:2017-11-22 22:10:26

标签: php arrays multidimensional-array

爵士

我有另一个问题..

我有两个Array和need数组在两个多维数组之间有所不同。

数组1:

Array
(
    [0] => Array
        (
            [0] => 2017-11-01
            [1] => Array
                (
                    [0] => 9 am
                    [1] => 11 am
                )

        )

    [1] => Array
        (
            [0] => 2017-11-02
            [1] => Array
                (
                    [0] => 05 pm
                    [1] => 07 pm
                    [2] => 08 pm
                )

        )

    [2] => Array
        (
            [0] => 2017-11-03
            [1] => Array
                (
                    [0] => 11 pm
                    [1] => 12 pm
                )

        )

    [3] => Array
        (
            [0] => 2017-11-04
            [1] => Array
                (
                    [0] => 02 pm
                    [1] => 03 pm
                )

        )

)

阵列二:

Array
(
    [0] => Array
        (
            [0] => 2017-11-01
            [1] => Array
                (
                    [0] => 9 am
                )

        )

    [1] => Array
        (
            [0] => 2017-11-03
            [1] => Array
                (
                    [0] => 11 pm
                )

        )

    [2] => Array
        (
            [0] => 2017-11-02
            [1] => Array
                (
                    [0] => 05 pm
                    [1] => 07 pm
                    [2] => 08 pm
                )

        )

    [3] => Array
        (
            [0] => 2017-11-04
            [1] => Array
                (
                    [0] => 02 pm
                    [1] => 03 pm
                )

        )

)

我需要通过上面两个数组之间的数组diff得到以下结果..

Array
(
    [0] => Array
        (
            [0] => 2017-11-01
            [1] => Array
                (
                    [0] => 11 am
                )

        )

    [2] => Array
        (
            [0] => 2017-11-03
            [1] => Array
                (
                    [0] => 12 pm
                )

        )

)

有没有简单的方法来解决这个问题。

提前致谢..

此致

安华

1 个答案:

答案 0 :(得分:0)

这里的想法是迭代第一个数组的所有元素,并将它与第二个数组中的相应元素进行比较(如果它们不同)。

$a = [
[
    'a',
    [
        'b',
        'c'
    ]
],
[
    'd',
    [
        'e',
        'f',
    ]
]
];

$b = [
[
    'a',
    [
        'b',
        'c'
    ]
],
[
    'd',
    [
        'h',
        'f'
    ]
]
];

function array_difference($a, $b) {
if( ! is_array($a)) {
    if($a != $b)
    echo "$a <> $b: " . $a . PHP_EOL;
    return;
}

$rowsA = count($a); $rowsB = count($b);
if( $rowsA !== $rowsB ) {
    echo 'Both arrays are not similar.' . PHP_EOL;
    exit(0);
}

for($i=0; $i < count($a) ; $i++) {
    array_difference($a[$i], $b[$i]);
}

}

print(array_difference($a, $b));