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函數。