将数组合并到php中另一个多数组的特定元素中

时间:2015-11-25 06:27:11

标签: php arrays

我有第一个看起来像这样的数组:

Array
(
[0] => Array
    (
        [data] => Array
            (
                [id] => 1
                [type] => asset 
                [description] => Real Estate
                [value] => 350000
            )
    )
)

第二个数组如下所示:

Array
(
[0] => Array
    (
        [owners] => Array
            (
                [data] => Array
                    (
                        [id] => 1
                        [percentage] => 100
                    )
            )
    )
)

我需要将第二个数组插入到'data'级别的第一个数组中,所以它看起来像这样:

Array
(
[0] => Array
    (
        [data] => Array
            (
                [id] => 1
                [type] => asset 
                [description] => Real Estate
                [value] => 350000
                [owners] => Array
                (
                    [data] => Array
                        (
                            [id] => 1
                            [percentage] => 100
                        )
                )
            )
    )
)

我已经尝试过array_merge,但输出并不像我预期的那样。将第二个数组正常追加到第一个数组只是将它添加到第一个数组的范围之外。

有人可以建议我如何在上面显示的级别添加第二个? THX

1 个答案:

答案 0 :(得分:2)

<?php 
    $array1 = Array("0" => Array("data" => Array( "id" => "1", "type" => "asset", "description" => "Real Estate", "value" => "350000" ) ) );

    $array2 = Array( "0" => Array ( "owners" => Array( "data" => Array( "id" => "1", "percentage" => "100") ) ) );

    // try this
    $array1[0]['data']['owners'] = $array2[0]['owners'];

    echo "<pre>"; print_r($array1);
?>

这将输出为

Array
(
    [0] => Array
        (
            [data] => Array
                (
                    [id] => 1
                    [type] => asset
                    [description] => Real Estate
                    [value] => 350000
                    [owners] => Array
                        (
                            [data] => Array
                                (
                                    [id] => 1
                                    [percentage] => 100
                                )

                        )

                )

        )

)

http://localhost/vote/singlevote/candidate-name