结合2阵列php

时间:2015-12-09 04:06:20

标签: php arrays multidimensional-array merge

Array
(
    [0] => Array
        (
            [id] => 123-456-000-000
            [name] => john
        )

    [1] => Array
        (
            [id] => 123-456-789-014
            [name] => james
        )

)
Array
(
    [0] => Array
        (
            [id] => 123-456-000-000
            [address] => Japan
        )

    [1] => Array
        (
            [tin] => 123-456-789-014
            [address] => Spain
        )

)

我上面有2个数组,我想将它们组合起来,所以我使用了array-merge。但我没有得到我想要的结果。它给了我的是

Array
(
    [0] => Array
        (
            [id] => 123-456-000-000
            [name] => john
        )

    [1] => Array
        (
            [id] => 123-456-789-014
            [name] => james
        )

    [2] => Array
        (
            [tin] => 123-456-000-000
            [address] => Japan
        )

    [3] => Array
        (
            [tin] => 123-456-789-014
            [address] => Spain
        )

)

我想要的是

Array
(
    [0] => Array
        (
            [id] => 123-456-000-000
            [name] => john
            [address] => Japan
        )

    [1] => Array
        (
            [id] => 123-456-789-014
            [name] => james
            [address] => Spain
        )

)

如何实现这种数组合并

2 个答案:

答案 0 :(得分:2)

假设两个数组具有相同数量的元素并且顺序相同,那么一个foreach循环可以完成这项工作

$arr1 = Array (
    0 => Array (
        "id" => "123-456-000-000",
        "name" => "john"
    ),
    1 => Array (
        "id" => "123-456-789-014",
        "name" => "james"
    )

);
$arr2 = Array (
    0 => Array (
        "tin" => "123-456-000-000",
        "address" => "Japan"
    ),
    1 => Array (
        "tin" => "123-456-789-014",
        "address" => "Spain"
    )
);

foreach ($arr2 as $key => $inner) {
    $arr1[$key]["address"] = $inner["address"];
}

输出:$arr1

Array
(
    [0] => Array
        (
            [id] => 123-456-000-000
            [name] => john
            [address] => Japan
        )

    [1] => Array
        (
            [id] => 123-456-789-014
            [name] => james
            [address] => Spain
        )

)

答案 1 :(得分:0)

假设您的数组大小相同,并且您的ID以相同的方式排序。

然后你可以尝试:

$arrayReturn = array();
foreach( $array1 as $key1 => $result1 ){
    $mergeArray = [$result1['id'], $result1['name'], $array2[$key1]['name']];
    array_push($arrayReturn, $mergeArray);
}

$ array1和$ array2都是我的初始数组。 $ arrayReturn是我的结果。 您是否没有其他方法可以在创建时直接合并数组?它将更加优雅,并将避免这一切。