简体   繁体   中英

Append array values to another array by keys comparison

I've this two arrays:

$arr1['someKey'] = [1,2,3,4,5];
$arr2['someKey'] = [6,7];

how do I add|append the values from the second one into the first one by comparing it's keys? The result should be something like:

$arr3['someKey'] = [1,2,3,4,5,6,7];

Any help?

Try array_merge_recursive :

$arr1 = array(
    'someKey' => [1,2,3,4,5],
);
$arr2 = array(
    'someKey' => [6,7],
);

$merged = array_merge_recursive($arr1, $arr2);

Ideone: http://ideone.com/0wfez8

Try this..

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

$arr3 = array_merge_recursive($arr1, $arr2);
print_r($arr3);

http://php.net/manual/en/function.array-merge-recursive.php

please check on your way should work.

$arr3 = $arr1 + $arr2; 

print_r($arr3);

as same as array_merge but preserved array keys.

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