如何将两个数组合并为一个

时间:2013-10-03 18:00:48

标签: php

我查看了这个网站并找到了一些合并数组的例子,但说实话,我不确定哪一个适合我。

我很难尝试合并这些数组。我已经尝试过array_combine和array_merge,但我没有运气。

我需要的是一个输出如下的单个数组:

Array
(
    [0] => Array
        (
            [UnitNo] => 91
            [Name] => Receiving
            [ActivityNo] =>
            [Active] => 2
            [CallNo] =>
            [CallStatusNo] =>
            [Assigned] =>
            [UnitId] => 2
        )
    [1] => Array
        (
            [UnitNo] => 83
            [Name] => Shipping
            [ActivityNo] =>
            [Active] =>
            [CallNo] =>
            [CallStatusNo] =>
            [Assigned] =>
            [UnitId] => 1
        )
)

这是我需要根据UnitId合并在一起的两个数组,这些数组应该形成一个完整的数组,如上所示。我只是不知道该怎么做。如果有人能指点我,我将不胜感激。

// Array #1
Array
(
    [0] => Array
        (
            [UnitId] => 2
            [UnitNo] => 91
            [Name] => Receiving
            [Active] => 4
        )

    [1] => Array
        (
            [UnitId] => 1
            [UnitNo] => 83
            [Name] => Shipping
            [Active] => 4
        )
)
// Array #2

Array
(
    [0] => Array
        (
            [UnitId] => 2
            [ActivityNo] => 1
            [CallNo] => 1
            [CallStatusNo] => 1
            [Assigned] => 1
        )

    [1] => Array
        (
            [UnitId] => 1
            [ActivityNo] => 11
            [CallNo] => 2
            [CallStatusNo] => 1
            [Assigned] => 1
        )

)

1 个答案:

答案 0 :(得分:0)

这不是你可以使用php函数并调用它的情况 - 你必须自己做一些自定义逻辑。

这可行,但前提是$array1$array2在每个索引处都有相同的项目。

$array1;
$array2;
$mergedArray;

for ($i=0; $i++; $i < count($array1) - 1) {
    //first add all the values from array1
    $mergedArray[$i] = $array1[$i];

    foreach($array2[$i] as $array2Key=>$array2Value){
        //now check for missing key/values that are in array2 but not in array1
        if (array_key_exists($array2Key, $array1[$i]) == false) {
            // the key does not exist in array1, so add it to mergedArray
            $mergedArray[$i][$array2Key] = $array2Value;
        }
    }
}

如果您的数组是关联数组,以唯一值索引,那么会更安全。