array_merge和array_merge_recursive是PHP中用于合并數組的兩個函數。它們的區別在于當數組鍵名沖突時的處理方式。
示例:
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "circle");
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
輸出:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => circle
)
示例:
$array1 = array("color" => array("favorite" => "red"), 2, 4);
$array2 = array("color" => array("favorite" => "green", "blue"), "a", "b");
$mergedArray = array_merge_recursive($array1, $array2);
print_r($mergedArray);
輸出:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 2
[1] => 4
[2] => a
[3] => b
)
綜上所述,array_merge和array_merge_recursive函數都可以用于合并數組,但在處理鍵名沖突時的方式不同。array_merge會覆蓋前面的鍵名,而array_merge_recursive會將相同鍵名的值以數組形式存儲。根據具體的需求選擇適合的函數進行數組合并操作。