0

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

我很难尝试合并这些数组。我试过 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
        )

)
4

1 回答 1

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;
        }
    }
}

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

于 2013-10-03T18:34:59.197 回答