众所周知PHP从7.4开始支持数组解构
$fruit = ['apple', 'banana'];
$color = ['blue', 'red'];
$array_unpacked = [...$fruit, ...$color, ...['yellow']];
$array_merged = array_merge($fruit, $color, ['yellow']);
可以看到数组解构跟 array_merge () 的结果是一样的,不过PHP7.4和PHP8.0的数组解构不支持关联数组,如果使用关联数组进行解构
$fruit = [
'fruit1' => 'apple',
'fruit2' => 'banana'
];
$color = [
'color1' => 'blue',
'color2' => 'red'
];
$array_unpacked = [...$fruit, ...$color];
会直接报错
Fatal error: Uncaught Error: Cannot unpack array with string keys
而PHP8.1开始支持关联数组的解构,运行上面的代码会得到正确的结果,并可以将数组解构用于动态取值中
$a = ['color1' => 'blue'];
$b = [];
$array = [
'fruit' => ['fruit1' => 'apple'],
...($a ? ['a' => $a] : []),
...($b ? ['b' => $b] : [])
];
当然我们知道加号运算符也可用于数组合并,那他跟数组解构来进行合并有什么区别呢?
$fruit = [
['fruit' => 'apple']
+['fruit' => 'banana']
];
$color = [
...['color' => 'blue'],
...['color' => 'red']
];
答案很明显,加号运算符会跳过相同 Key 的值,而数组解构合并会覆盖相同 Key 的值