How to combine multidimensional array in php?

Scout APM helps PHP developers pinpoint N+1 queries, memory leaks & more so you can troubleshoot fast & get back to coding faster. Start your free 14-day trial today.

If you want to join two multidimensional arrays in PHP, you should still use array_merge, and not array_merge_recursive. Confused? So was I. Let's explain what's happening.

Let's first explain what array_merge_recursive does, take for example these two arrays:

$first = [
    'key' => 'original'
];

$second = [
    'key' => 'override'
];

Using array_merge_recursive will result in the following:

array_merge_recursive($first, $second);

// [
//     'key' => [
//         'original',
//         'override',
//     ],
// ]

Instead over overriding the original key value, array_merge_recursive created an array, with the original and new value both in it.

While that looks strange in this simple example, it's actually more useful in cases where one of the values already is an array, and you want to merge another item in that array, instead of overriding it.

$first = [
    'key' => ['original']
];

$second = [
    'key' => 'override'
];

In this case, array_merge_recursive will yield the same result as the first example: it takes the value from the $second array, and appends it to the value in the $first array, which already was an array itself.

array_merge_recursive($first, $second);

// [
//     'key' => [
//         'original',
//         'override',
//     ],
// ]

So if you want to merge multidimensional arrays, you can simply use array_merge, it can handle multiple levels of arrays just fine:

$first = [
    'level 1' => [
        'level 2' => 'original'
    ]
];

$second = [
    'level 1' => [
        'level 2' => 'override'
    ]
];

array_merge($first, $second);

// [  
//     'level 1' => [
//         'level 2' => 'override'
//     ]
// ]

All of that being said, you could also use the + operator to merge multidimensional arrays, but it will work slightly different compared to array_merge.

Noticed a tpyo? You can submit a PR to fix it. If you want to stay up to date about what's happening on this blog, you can follow me on Twitter or subscribe to my newsletter:

Either I'm blind or I can't find this problem anywhere here on SO. Yesterday I had a problem with merging arrays, which I could fix with the help of SO. Today I have, again, a problem with merging arrays, but this time it's with multidimensional Arrays.

I have an array $usergroup['groups'] and an array $usergroup['lang']

$usergroup['groups'] looks like this:

Array
(
    [0] => Usergroup_Model Object
        (
            [id] => 1
            [deleted] => 0
        )

    [1] => Usergroup_Model Object
        (
            [id] => 2
            [deleted] => 0
        )

    [2] => Usergroup_Model Object
        (
            [id] => 3
            [deleted] => 0
        )

)

And $usergroup['lang'] looks like this:

Array
(
    [0] => Usergroup_Model Object
        (
            [id] => 
            [id_usergroup] => 1
            [name] => Administratoren
            [id_lang] => 1
        )

    [1] => Usergroup_Model Object
        (
            [id] => 
            [id_usergroup] => 2
            [name] => Benutzer
            [id_lang] => 1
        )

    [2] => Usergroup_Model Object
        (
            [id] => 
            [id_usergroup] => 3
            [name] => Gäste
            [id_lang] => 1
        )

)

I want my merged array to look like this:

Array
(
    [0] => Usergroup_Model Object
        (
            [id] => 1
            [id_usergroup] => 1
            [name] => Administratoren
            [id_lang] => 1
            [deleted] => 0
        )

    [1] => Usergroup_Model Object
        (
            [id] => 2
            [id_usergroup] => 2
            [name] => Benutzer
            [id_lang] => 1
            [deleted] => 0
        )

    [2] => Usergroup_Model Object
        (
            [id] => 3
            [id_usergroup] => 3
            [name] => Gäste
            [id_lang] => 1
            [deleted] => 0
        )

)

What have I tried?

I've tried several merging functions (array_merge() and array_merge_recursive()) of PHP, the closest result I got was, that the second Array (['lang']) overwrote the first Array (['groups']). To fix that, I tried to remove the empty values on the lang Array (which is always id). But that does not fix it. The code - at the moment - looks like this:

public static function getAll()
{
  $usergroup['groups'] = self::find();
  $usergroup['lang'] = self::findInTable(array(
    'id_lang' => Language_Model::getDefaultLanguage()
  ), self::dbTranslationTable);
  foreach ($usergroup as $ug) {
    $ug = array_filter($ug, function($val) {
      return $val != '';
    });
  }
  return array_merge($ug);
}

The array_merge() on the return command doesn't seem to do anything at all, so I'm probably not gathering the data correctly or I mess something up with the Arrays (forgetting to add [], or I don't know...). I kinda miss the forest for the trees here.

Any suggestions in which direction I could go?

Edit: With the code provided by Pé de Leão I was able to solve the problem. My function now looks like this:

public static function getAll()
{
  $usergroup['groups'] = self::find();
  $usergroup['lang'] = self::findInTable(array(
    'id_lang' => Language_Model::getDefaultLanguage()
  ), self::dbTranslationTable);
  $out = array();
  foreach ($usergroup['groups'] as $key => $value) {
    $out[] = (object) array_merge((array) $usergroup['lang'][$key], (array) $value);
  }
  return $out;
}

And the result is exactly how I wanted it!

How will you merge two multidimensional arrays to get the required outcome?

Using NumPy, we can perform concatenation of multiple 2D arrays in various ways and methods..
Method 1: Using concatenate() function..
Method 2: Using stack() functions:.
Method 3: Using hstack() function..
Method 4: Using vstack() function..
Method 5: Using dstack() function..

How can I merge two arrays in PHP?

The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.

How can I merge three arrays in PHP?

PHP array_merge() Function $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2));

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.