phparraysmultidimensional-arraymerging-data

Merge row data from two 2d arrays related by first level keys


How I can merge/push one array to another to specific keys? Here are my arrays:

// Array 1
Array
(
    [1] => Array
        (
            [name] => test
        )
)

// Array 2
Array
(
    [1] => Array
        (
            [age] => 25
        )
)

I want this result:

Array
(
    [1] => Array
        (
            [name] => test
            [age] => 25
        )
)

Solution

  • $arr = [ 1 => [ "name" => "Test" ] ];
    $arr2 = [ 1 => [ "age" => 25 ] ];
    
    foreach ($arr as $key => $value) {
         if (isset($arr2[$key])) {
            $arr[$key] = array_merge($value,$arr2[$key]);
         }
    }
    
    print_r($arr);
    

    3v4l link