简体   繁体   中英

PHP merge 2 array with same key

Hi everyone how I can merge/push one array to another to specific keys? Here is 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
        )
)

I use PHP and will be very grateful if someone help me. Thanks in advance!

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

Check the output at https://eval.in/602680

Just add them together:

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

var_dump($array1 + $array2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM