phparraysrecursionmultidimensional-arraymerging-data

Merge multple 2d associative arrays into one consolidated 2d associative array


I have a somewhat complicated function that builds an array structure dynamically to insert fields into MongoDB. We store the structure in MySQL.

The function outputs the following array structure:

Array
(
    [address] => Array
        (
            [street] => 10 Stack St
        )

)

Array
(
    [address] => Array
        (
            [city] => Overflow Mountains
        )

)
    Array
(
    [address] => Array
        (
            [state] => CM
        )

)
Array
(
    [address] => Array
        (
            [zip] => 01010
        )

)

I need to merge these arrays so it looks like

[address] => Array
    (
        [street] => 10 Stack St
        [city] => Overflow Mountains
        [state] => CM
        [zip] => 01010
    )

How would I go about doing this?


Solution

  • You can use array_replace_recursive().

    Let your arrays be $array1, $array2, $arrray3, $array4

    You can try

    array_replace_recursive($array1, $array2, $array3, $array4);
    

    Hope this helps