Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, Merge keys in multidimensional array

Tags:

arrays

php

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?

I Hope this makes any sort of sense and thanks in advance for any help i can get.

like image 479
user2319551 Avatar asked Apr 25 '13 11:04

user2319551


1 Answers

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.

like image 181
Jon Avatar answered Nov 14 '22 15:11

Jon