0

I'm trying to merge inner keys of a php array. There may be some instances of the loop that creates this array where the same key is generated in a different iteration of the loop.

I'm using this method to create my big array:

foreach ( $repeater as $file ) : if ($file) :
    loop stuff here;
    $fileArray[$parentCat][$fileCategoryName][] = $theFile;
endif; endforeach;

$postFiles[] = $fileArray; // inside a bigger loop to collect all data

I'm trying to merge the $parentCat of the array building process.

Example of result array:

Array (
    [0] => Array (
        [Category Name] => Array (
            [Sub Category] => Array (
                'fieldvalue' => 'fieldvalue',
            ),
        ),   
    ),
    [1] => Array (
        [Category Name] => Array (
            [Different Sub Category] => Array (
                'differentfieldvalue' => 'differentfieldvalue',
            ),
        ),   
    ),      
),

I want to merge the Category Name so that it looks something like this:

Array (
    [0] => Array (
        [Category Name] => Array (
            [Sub Category] => Array (
                'fieldvalue' => 'fieldvalue',
            ),
            [Different Sub Category] => Array (
                'differentfieldvalue' => 'differentfieldvalue',
            ),
        ),   
    ),     
),

I've tried using array_merge_recursive, array_merge, and a few other ways with no success. I'm thinking it's something simple that I'm over looking.

2
  • You should solve it by using foreach loop. Have you already tried it? Commented Nov 18, 2015 at 17:19
  • I had tried to merge them with a foreach loop afterwards without success. I marked Alexandre's answer below correct as it solved the issue - and quite simply thankfully. Commented Nov 18, 2015 at 17:41

1 Answer 1

1

array_merge_recursive is the right way to go. But you can't call it with an array of arrays, you need to call it with a list of arrays.

Try the following, that should solve your problem:

$mergedPostFiles = call_user_func_array('array_merge_recursive', $postFiles);
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome that worked! Thank you so much. I had never even seen 'call_user_func_array' function before.
This is a function that calls a callback. There's a whole set of function in PHP that offer you different ways to manipulate existing functions. call_user_func_array is particularly useful when you want to use an array as a list of parameters. Have a look at these: php.net/manual/en/ref.funchand.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.