陣列合併是高頻操作,但 array_merge()、array_merge_recursive()、array_splice()、+ 運算子行為差異極大,選錯會導致資料遺失或結構錯亂。本文系統對比四大合併方式,提供決策流程圖與實戰範例。
| 函式/運算子 | 數值索引 | 字串鍵名衝突 | 巢狀陣列 | 原陣列修改 | 回傳值 |
|---|---|---|---|---|---|
array_merge() | 重新索引 (0,1,2...) | 後者覆蓋前者 | 不遞迴(視為值覆蓋) | 否(回傳新陣列) | 新陣列 |
array_merge_recursive() | 重新索引 | 合併為陣列 | 遞迴合併 | 否 | 新陣列 |
array_splice() | 就地修改索引 | 不適用(僅數值索引) | 不適用 | 是(修改原陣列) | 被移除元素組成的陣列 |
+ 運算子 | 保留原索引 | 前者優先(不覆蓋) | 不遞迴 | 否 | 新陣列 |
<?php
$fruits = ['apple', 'banana', 'pear'];
$numbers = ['1', '2', '3'];
$merged = array_merge($fruits, $numbers);
// ['apple', 'banana', 'pear', '1', '2', '3'] 索引 0~5
?>
<?php
$defaults = ['host' => 'localhost', 'port' => 3306, 'debug' => false];
$config = ['port' => 5432, 'user' => 'admin'];
$final = array_merge($defaults, $config);
// ['host' => 'localhost', 'port' => 5432, 'debug' => false, 'user' => 'admin']
?>
<?php
$a = [5 => 'a', 6 => 'b'];
$b = [7 => 'c'];
print_r(array_merge($a, $b));
// [0 => 'a', 1 => 'b', 2 => 'c'] 索引歸零!
?>
保留索引請用 + 運算子。
<?php
$defaultConfig = [
'database' => [
'host' => 'localhost',
'port' => 3306,
],
'cache' => ['redis'],
];
$envConfig = [
'database' => [
'host' => 'db.prod',
'ssl' => true,
],
'cache' => ['memcached'],
];
$merged = array_merge_recursive($defaultConfig, $envConfig);
/*
[
'database' => [
'host' => ['localhost', 'db.prod'], // 衝突變陣列!
'port' => 3306,
'ssl' => true,
],
'cache' => ['redis', 'memcached'], // 數值索引合併
]
*/
?>
字串鍵衝突會自動包裝成陣列,導致後續存取需判斷是純值還是陣列。配置合併建議用專用套件(如 symfony/config)或自寫深度合併函式。
array_splice(array &$array, int $offset, int $length = null, mixed $replacement = []): array<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Pear', 'Grape'];
// 1. 從索引 4 開始移除至結尾
$removed = array_splice($fruits, 4);
// $fruits = ['Apple', 'Banana', 'Orange', 'Pear']
// $removed = ['Grape']
// 2. 替換:移除索引 2~3,插入新元素
$fruits = ['Apple', 'Banana', 'Orange', 'Pear', 'Grape'];
$removed = array_splice($fruits, 2, 2, ['Green Apple', 'Red Apple']);
// $fruits = ['Apple', 'Banana', 'Green Apple', 'Red Apple', 'Grape']
// $removed = ['Orange', 'Pear']
// 3. 僅插入(length=0)
$fruits = ['Apple', 'Banana', 'Pear'];
array_splice($fruits, 2, 0, ['Orange']); // 指定位置插入
// ['Apple', 'Banana', 'Orange', 'Pear']
?>
$offset 支援負數(從尾部倒數)。$length 省略 = 移除至結尾;0 = 僅插入。$replacement 可為單一值(自動包裝陣列)或陣列。<?php
$a = ['a' => 1, 'b' => 2, 5 => 'x'];
$b = ['b' => 20, 'c' => 3, 5 => 'y'];
$union = $a + $b;
// ['a' => 1, 'b' => 2, 5 => 'x', 'c' => 3]
// 索引 5 保留 $a 的值,不重新索引
?>
需要合併陣列 │ ├─ 需修改原陣列、切片/插入/刪除? → array_splice() │ ├─ 需遞迴合併巢狀結構? → array_merge_recursive()(小心陣列化) │ ├─ 數值索引需重新排序(0,1,2...)? → array_merge() │ ├─ 需保留原索引、鍵衝突保留第一個? → + 運算子 │ └─ 複雜深度合併邏輯? → 自寫遞迴函式或用套件
<?php
function deepMerge(array $base, array $override): array {
foreach ($override as $key => $value) {
if (
isset($base[$key]) &&
is_array($base[$key]) &&
is_array($value)
) {
$base[$key] = deepMerge($base[$key], $value);
} else {
$base[$key] = $value; // 覆蓋或新增
}
}
return $base;
}
$default = [
'app' => ['debug' => false, 'locale' => 'en'],
'db' => ['host' => 'localhost', 'port' => 3306],
];
$env = [
'app' => ['debug' => true],
'db' => ['port' => 5432, 'charset' => 'utf8mb4'],
];
$config = deepMerge($default, $env);
/*
[
'app' => ['debug' => true, 'locale' => 'en'],
'db' => ['host' => 'localhost', 'port' => 5432, 'charset' => 'utf8mb4'],
]
*/
?>
陣列合併無銀彈,關鍵在於明確需求:要不要重新索引?衝突怎麼處理?需不需要遞迴?修不修改原陣列?將本文決策流程圖收藏,下次合併陣列不再靠直覺、只靠規格。