phparraysmultidimensional-arraymerging-data

Merge deep rows of an array with 3 levels by second level keys


If I have an array which looks something like this:

Array
(
    [0] => Array
    (
        [DATA] => Array
        (
            VALUE1 = 1
            VALUE2 = 2
        )
    )
    [1] => Array
    (   
        [DATA] => Array
        (
            VALUE3 = 3
            VALUE4 = 4
        )
    )
)

And would like to turn it into this:

Array
(
    [0] => Array
    (
        [DATA] => Array
        (
            VALUE1 = 1
            VALUE2 = 2
            VALUE3 = 3
            VALUE4 = 4
        )
    )
)

I basically want to merge all the identical keys which are at the same level. What would be the best route to accomplish this? Could the array_merge() functions be of any use?


Solution

  • You can use array_merge_recursive to merge all the items in your original array together. And since that function takes a variable number of arguments, making it unwieldy when this number is unknown at compile time, you can use call_user_func_array for extra convenience:

    $result = call_user_func_array('array_merge_recursive', $array);
    

    The result will have the "top level" of your input pruned off (logical, since you are merging multiple items into one) but will keep all of the remaining structure.

    See it in action.