php - 合并数组保持arr1中的值重复

时间:2015-01-11 11:16:54

标签: php arrays loops foreach

我有2个数组arr1arr2。我想合并它们而不复制或覆盖arr1中的数组值。

arr1
(
    [0] => Array (
    [aName] => Doe jones
    [ref] => 3
    [afield] => 01-06-2015
    )

    [1] => Array (
    [aName] => John doe
    [ref] => 5
    [afield] => 01-10-2015
    )

    [2] => Array (
    [aName] => Peter Griffin
    [ref] => 7
    [afield]
    )

)
arr2
(
    [0] => Array (
    [aName] => Doe jones
    [ref] => null
    [afield] => null
    )

    [1] => Array (
    [aName] => John doe
    [ref] => null
    [afield] => null
    )

    [2] => Array (
    [aName] => Peter Griffin
    [ref] => null
    [afield] => null
    )

    [3] => Array (
    [aName] => Stuart Griffin
    [ref] => null
    [afield] => null
    )

)

期望的输出:

newArr
(
    [0] => Array (
    [aName] => Doe jones
    [ref] => 3
    [afield] => 01-06-2015
    )

    [1] => Array (
    [aName] => John doe
    [ref] => 5
    [afield] => 01-10-2015
    )

    [2] => Array (
    [aName] => Peter Griffin
    [ref] => 7
    [afield]
    )

    [3] => Array (
    [aName] => Stuart Griffin
    [ref] => null
    [afield] => null
    )

)

我已经设法通过一系列嵌套的foreach循环和if语句来实现这一目标。然而,这似乎是执行此任务的一种非常低效的方式。

我认为以下功能组合可行,但它没有所需的结果

$newArray = array_unique(array_merge($arr1, $arr2));

1 个答案:

答案 0 :(得分:0)

您不能使用这种方法来执行您想要的操作,因为您有一些功能规则,例如合并具有相同名称的项目而不是空值擦除空值。 array_merge和array_unique无法识别该规则。

您可以使用这种功能:

function mergeArray(array $arr1, array $arr2) {
    $mergedArray = array();

    foreach ($arr1 as $item1) {
        $mergedArray[$item1['aName']] = $item1;
    }

    foreach ($arr2 as $item2) {
        if (!isset($mergedArray[$item2['aName']]) {
            $mergedArray[$item2['aName']] = $item2;
        } else {
            $item = $mergedArray[$item2['aName']];
            foreach ($item as $key => $value) {
                if (null === $value && isset($item2[$key])) {
                    $mergedArray[$item2['aName']][$key] = $item2[$key];
                }
            }
        }
    }

    return $mergedArray;
}