phparraysarray-combine

combine 2 array with same key into 1 array


I have 2 Array:

$arr1 = Array (
         [2] => Array ( [0] => 41000 [1] => 31079 ) 
         [3] => Array ( [0] => 42963 [1] => 41189 ) 
    )

$arr2 = Array ( 
        [2] => Array ( [0] => 40213 [1] => 42054 ) 
        [3] => Array ( [0] => 42998 [1] => 34567 ) 
    )

I want to combine these two arrays to this array with same key:

$arr3 = Array ( 
        [2] => Array ( [0] => 40213 [1] => 42054 [2] => 41000 [3] => 31079 ) 
        [3] => Array ( [0] => 42998 [1] => 34567 [2] => 42963 [3] => 41189 ) 
    )

I tried almost anything (merge, combine, join) but I can't figure it out. Any suggestions?


Solution

  • This is a nice and easy thing to do.

    $arr1 = [2 => [0 => 41000, 1 => 31079], 3 => [0 => 42963, 1 => 41189]];
    $arr2 = [2 => [0 => 40213, 1 => 42054], 3 => [0 => 42998, 1 => 34567]];
    
    function addArray(&$bucket, $water)
    {
        foreach ($water as $key => $drop) {
            $bucket[$key] = array_merge($bucket[$key] ?? [], $drop);
        }
    }
    
    $combined = [];
    addArray($combined, $arr1);
    addArray($combined, $arr2);
    
    var_export($combined);
    

    See a PHP fiddle here.

    The output is:

    array (
      2 => 
      array (
        0 => 41000,
        1 => 31079,
        2 => 40213,
        3 => 42054,
      ),
      3 => 
      array (
        0 => 42963,
        1 => 41189,
        2 => 42998,
        3 => 34567,
      ),
    )
    

    How does it work? I wrote a little function that would add the input arrays to an array that combines all arrays.