如何在PHP中找到两个大小和级别不同的多维数组之间的差异

oknwwptz  于 2023-01-16  发布在  PHP
关注(0)|答案(1)|浏览(103)

我在php中有两个不同大小和级别的多维数组。我需要在第二个数组中找到第一个数组中没有的元素。

阵列A:

$bmw_a = array(
    "3 series" => array(),
    "5 series" => array(
        "520D" => array(
            "N47_163" => array(),
        ),
        "530i" => array(),
    ),
    "7 series" => array(),
);

阵列B:

$bmw_b = array(
    "1 series" => array(),
    "3 series" => array(),
    "5 series" => array(
        "520D" => array(
            "N47_163" => array(),
            "M47_177" => array()
        ),
        "530i" => array(
            "M54_228" => array(),
            "N52_255" => array()
        ),
    ),
    "7 series" => array(),
);

我需要输出如下所示:

$output = array(
    "1 series" => array(),
    "5 series" => array(
        "520D" => array(
            "M47_177" => array()
        ),
        "530i" => array(
            "M54_228" => array(),
            "N52_255" => array()
        )
    )
);

我尝试了array_diffarray_diff_assoc,但没有一个工作。

xlpyo6sf

xlpyo6sf1#

array_diff_assoc()只在一个级别上工作,因此对于多维数组,您需要递归。

在这里

<?php

$bmw_a = array(
    "3 series" => array(),
    "5 series" => array(
        "520D" => array(
            "N47_163" => array(),
        ),
        "530i" => array(),
    ),
    "7 series" => array(),
);

$bmw_b = array(
    "1 series" => array(),
    "3 series" => array(),
    "5 series" => array(
        "520D" => array(
            "N47_163" => array(),
            "M47_177" => array()
        ),
        "530i" => array(
            "M54_228" => array(),
            "N52_255" => array()
        ),
    ),
    "7 series" => array(),
);

$result = array_diff_assoc_recursive($bmw_b, $bmw_a);

echo '<pre>';
var_dump($result);

function array_diff_assoc_recursive($array1, $array2) {
    $diff = array();
    foreach ($array1 as $key => $value) {
        if (is_array($value)) {
            if (!isset($array2[$key]) || !is_array($array2[$key])) {
                $diff[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if (!empty($new_diff)) {
                    $diff[$key] = $new_diff;
                }
            }
        } elseif (!isset($array2[$key]) || $array2[$key] != $value) {
            $diff[$key] = $value;
        }
    }
    return $diff;
}

输出:

array(2) {
  ["1 series"]=>
  array(0) {
  }
  ["5 series"]=>
  array(2) {
    ["520D"]=>
    array(1) {
      ["M47_177"]=>
      array(0) {
      }
    }
    ["530i"]=>
    array(2) {
      ["M54_228"]=>
      array(0) {
      }
      ["N52_255"]=>
      array(0) {
      }
    }
  }
}

相关问题