可以使用array_merge_recursive()函數來合并多維數組中相同的鍵。
示例代碼如下:
$array1 = array(
"color" => array("favorite" => "red"),
"food" => array("fruit" => "apple", "vegetable" => "carrot")
);
$array2 = array(
"color" => array("favorite" => "blue"),
"food" => array("fruit" => "banana")
);
$result = array_merge_recursive($array1, $array2);
print_r($result);
輸出結果為:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => blue
)
)
[food] => Array
(
[fruit] => Array
(
[0] => apple
[1] => banana
)
[vegetable] => carrot
)
)
在合并過程中,相同的鍵會被合并為一個數組,然后是其他鍵值對的合并。