1. array_merge_recursive
array_merge_recursive — 递归地合并一个或多个数组
<?php
$first = [
'key' => 'No1'
];
$second = [
'key' => 'No2'
];
print_r(array_merge_recursive($first, $second));
结果:
Array
(
[key] => Array
(
[0] => No1
[1] => No2
)
)
<?php
$first = [
'key' => 'No1',
'key1' => 'key1',
'key2' => 'key2'
];
$second = [
'key' => 'No2',
'key1' => 'key2'
];
print_r(array_merge_recursive($first, $second));
结果:
Array
(
[key] => Array
(
[0] => No1
[1] => No2
)
[key1] => Array
(
[0] => key1
[1] => key2
)
[key2] => key2
)
2. array_merge
array_merge:后面的数组的value会覆盖前面数组的value值
<?php
$first = [
'key' => 'No1',
'key1' => 'key1',
'key2' => 'key2'
];
$second = [
'key' => 'No2',
'key1' => 'key2'
];
print_r(array_merge($first, $second));
Array
(
[key] => No2
[key1] => key2
[key2] => key2
)
3. array+array
array+array两个数组合并保留前面的数组,同时新增后面数组中新的索引和值
<?php
$first = [
'a',
'b',
'c' => 2
];
$second = [
'c' => 1,
'd' => 3,
'4'
];
print_r($first + $second);
结果:
Array
(
[0] => a
[1] => b
[c] => 2
[d] => 3
)
注解:之所以没有保留第二个数组中的4,是因为 s e c o n d 里 的 4 对 应 的 数 字 索 引 是 0 , 也 就 是 0 = > ′ 4 ′ , 而 second里的4对应的数字索引是0,也就是0=>'4',而 second里的4对应的数字索引是0,也就是0=>′4′,而first的数字索引是0=>’a’,1=>’b’,打印如下:
$first = [
0 => 'a',
1 => 'b',
];
$second = [
0 => '4',
];
所以4没有出现在数组中,为了更进一步直观验证,可以在$second里新增几个值
<?php
$first = [
'a',
'b',
'c' => 2
];
$second = [
'c' => 1,
'd' => 3,
'4',
5,
6
];
print_r($first + $second);
结果:
Array
(
[0] => a
[1] => b
[c] => 2
[d] => 3
[2] => 6
)