diank
diank

Reputation: 638

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
        )
)

Upvotes: 0

Views: 50

Answers (3)

apokryfos
apokryfos

Reputation: 40653

$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

Upvotes: 1

mickmackusa
mickmackusa

Reputation: 47864

You can traverse the first array and use the array union assignment operator and the null coalescing operator to append related values from the second array to the first array. Demo

foreach ($arr1 as $k => &$v) {
    $v += $arr2[$k] ?? [];
}
var_export($arr1);

Upvotes: 0

R. Chappell
R. Chappell

Reputation: 1282

Just add them together:

<?php
$array1 = array('name' => 'test');
$array2 = array('age' => 21);

var_dump($array1 + $array2);

Upvotes: -1

Related Questions