PHP中合并数组的方法有以下几种:
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("c" => "cat", "d" => "dog");
$result = $array1 + $array2;
print_r($result);
结果:
Array
(
[a] => apple
[b] => banana
[c] => cat
[d] => dog
)
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("c" => "cat", "d" => "dog");
$result = array_merge($array1, $array2);
print_r($result);
结果:
Array
(
[a] => apple
[b] => banana
[c] => cat
[d] => dog
)
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("b" => "blue", "c" => "cat");
$result = array_merge_recursive($array1, $array2);
print_r($result);
结果:
Array
(
[a] => apple
[b] => Array
(
[0] => banana
[1] => blue
)
[c] => cat
)
需要注意的是,上述方法中的数组合并都是将后面的数组追加到前面的数组,如果想要同时保留相同键名的元素,可以使用array_replace或array_replace_recursive函数。