Home > Software design >  combine 2 array with same key into 1 array
combine 2 array with same key into 1 array

Time:09-29

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?

CodePudding user response:

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.

CodePudding user response:

    $arr1 = array(
        2 => array(41000, 31079),
        3 => array(42963, 41189)
    );

    $arr2 = array(
        2 => array(40213, 42054),
        3 => array(42998, 34567)
    );

    $arr3 = array();

    foreach($arr1 as $key => $values){
        if(!isset($arr3[$key])){
            $arr3[$key] = array();
        }
        $arr3[$key] = array_merge($arr3[$key], $values);
    }

    foreach($arr2 as $key => $values){
        if(!isset($arr3[$key])){
            $arr3[$key] = array();
        }
        $arr3[$key] = array_merge($arr3[$key], $values);
    }

    echo '<pre>';
    print_r($arr3);

Prints:

Array
(
    [2] => Array
        (
            [0] => 41000
            [1] => 31079
            [2] => 40213
            [3] => 42054
        )

    [3] => Array
        (
            [0] => 42963
            [1] => 41189
            [2] => 42998
            [3] => 34567
        )

)
  • Related