php合并数组一般有三个方法
array_merge
函数array_merge_recursive
函数+
array_merge
与+
的比较+
操作以前面的数组为准+
操作处理数字索引的策略和处理字符串索引一致:以前面的数组为准,且保留原索引array_merge
与array_merge_recursive
的比较$arr1 = [
2 => 'super',
1 => 'star',
'hello' => 'my world',
'arr' => [
3 => 'ha',
2 => 'ya',
'hello' => 'wa',
]
];
$arr2 = [
1 => 'lets',
2 => 'laugh',
'hello' => 'your world',
'arr' => [
'yes no'
]
];
print_r(array_merge($arr1, $arr2));
print_r($arr1 + $arr2);
print_r(array_merge_recursive($arr1, $arr2));
以上代码输出为:
Array
(
[0] => super
[1] => star
[hello] => your world
[arr] => Array
(
[0] => yes no
)
[2] => lets
[3] => laugh
)
Array
(
[2] => super
[1] => star
[hello] => my world
[arr] => Array
(
[3] => ha
[2] => ya
[hello] => wa
)
)
Array
(
[0] => super
[1] => star
[hello] => Array
(
[0] => my world
[1] => your world
)
[arr] => Array
(
[3] => ha
[2] => ya
[hello] => wa
[3] => yes no
)
[2] => lets
[3] => laugh
)
在7.0.20版本中,array_merge_recursive合并相同字符串索引的数组时,合并结果中会有相同的数字索引。
$arr1 = [
'arr' => [
3 => 'hello',
2 => 'world',
]
];
$arr2 = [
'arr' => [
'yes',
'no'
]
];
$result = array_merge_recursive($arr1, $arr2);
print_r($result);
以上代码会输出:
Array
(
[arr] => Array
(
[3] => hello
[2] => world
[2] => yes
[3] => no
)
)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。