Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
This is the best answer you're going to have here. –  Tomasz Kowalczyk Apr 25 '13 at 12:06
    
I was wondering if there was a way to do this without a writing out a loop - very tidy! –  lewsid Apr 25 '13 at 12:06
    
This did the trick! Thank you! –  user2319551 Apr 25 '13 at 12:08
    
BEST. ANSWER. EVER! Hahahaha –  Brian Coolidge May 2 at 5:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.