在PHP中,有幾種不同的方式可以合并數組。以下是常見的幾種方法:
示例:
$array1 = array("a", "b", "c");
$array2 = array("d", "e", "f");
$result = array_merge($array1, $array2);
print_r($result);
輸出:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
示例:
$array1 = array("a", "b", "c");
$array2 = array("d", "e", "f");
$result = $array1 + $array2;
print_r($result);
輸出:
Array
(
[0] => a
[1] => b
[2] => c
[3] => f
)
示例:
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("a" => "ant", "b" => "bat");
$result = array_merge_recursive($array1, $array2);
print_r($result);
輸出:
Array
(
[a] => Array
(
[0] => apple
[1] => ant
)
[b] => Array
(
[0] => banana
[1] => bat
)
)
這些是常見的合并數組的方式,在不同的情況下可以選擇適合的方法來實現合并。