PHP中合并數(shù)組的方法有以下幾種:
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("c" => "cat", "d" => "dog");
$result = $array1 + $array2;
print_r($result);
結(jié)果:
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);
結(jié)果:
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);
結(jié)果:
Array
(
[a] => apple
[b] => Array
(
[0] => banana
[1] => blue
)
[c] => cat
)
需要注意的是,上述方法中的數(shù)組合并都是將后面的數(shù)組追加到前面的數(shù)組,如果想要同時保留相同鍵名的元素,可以使用array_replace或array_replace_recursive函數(shù)。