https://www.php.net/array_merge
array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。
示例
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
var_dump($result);
array(7) {
[“color”] => string(5) “green”
[0] => int(2)
[1] => int(4)
[2] => string(1) “a”
[3] => string(1) “b”
[“shape”] => string(9) “trapezoid”
[4] => int(4)
}
数字变成字符转同样会强制转换成数字【坑坑】
$array1 = array("1" => "red");
$array2 = array("1"=>'green');
$result = array_merge($array1, $array2);
var_dump($result);
$array1 = array("q1" => "red");
$array2 = array("q1"=>'green');
$result = array_merge($array1, $array2);
var_dump($result);
array(2) {
[0] => string(3) “red”
[1] => string(5) “green”
}
array(1) {
[“q1”] => string(5) “green”
}
array_merge 与 “+” 的区别
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = array_merge($array1, $array2);
var_dump($result);
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
array(6) {
[0] => string(6) “zero_a”
[1] => string(5) “two_a”
[2] => string(7) “three_a”
[3] => string(5) “one_b”
[4] => string(7) “three_b”
[5] => string(6) “four_b”
array(5) {
[0] => string(6) “zero_a”
[2] => string(5) “two_a”
[3] => string(7) “three_a”
[1] => string(5) “one_b”
[4] => string(6) “four_b”
}