yoyoma
yoyoma

Reputation: 3536

Merging array into specific element of another multi array in php

I have first array that looks like such:

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

A second array looks like this:

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

I need to insert the 2nd array into the first at the level of 'data' so it looks like this:

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

I've tried array_merge, but the output is not as I expect. A normal appending of the 2nd array to first just adds it outside the scope of the first.

Can anyone advise how I would add the 2nd at the level displayed above ? thx

Upvotes: 1

Views: 35

Answers (1)

Suyog
Suyog

Reputation: 2482

<?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);
?>

This will give output as

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

                        )

                )

        )

)

See Working link

Upvotes: 2

Related Questions