+
) 補充合併陣列 (+
) 補充,在 What is the difference between array_merge and array + array in PHP? 一文中,一個範例如下:
'four' => 4,
,怎麼會這樣?! 'four' => 4, 12, 13, 14, 15
的 12, 13, 14, 15 到哪去!'two' => 2, 10, 11, 12, 13
之中,左側陣列的 $arr1 index 分別為:
+
$arr2 合併的 $arr4 'four' 只會顯示 4
'two'
的 index 0 ~ 3 顯示 value 取代 $arr2 'four' 的 index 0 ~ 34
,array index 0 ~ 3 的 value 是 12, 13, 14, 15,請閱讀 PHP 文件-Arrays規範
<?php
// 範例
$arr1 = array( 'zero' => 0,
'one' => 1,
'two' => 2, 10, 11, 12, 13
);
$arr2 = array( 'one' => 11,
'three' => 3,
'four' => 4, 12, 13, 14, 15
);
$arr4 = $arr1 + $arr2;
print_r($arr4);
/* 我以為的 $arr4: (
* 'zero' => 0,
* 'one' => 1,
* 'two' => 2, 10, 11, 12, 13
* 'three' => 3,
* 'four' => 4, 12, 13, 14, 15
* )
*/
/* 實際拿到的 $arr4: (
* 'zero' => 0,
* 'one' => 1,
* 'two' => 2,
* [0] => 10,
* [1] => 11,
* [2] => 12,
* [3] => 13
* 'three' => 3,
* 'four' => 4,
* )
*/
12, 13, 14, 15
,可以怎麼做(排除使用 php function array_merge()
)?
<?php
// 方式1
$arr2 = array( 'one' => 11,
'three' => 3,
4 => 4, 12, 13, 14, 15
);
// [4] => 4, [5] => 12, [6] => 13, [7] => 14, [8] => 15
// 方式2
$arr2 = array( 'one' => 11,
'three' => 3,
'four' => 4,
4 => 12, 13, 14, 15
);
// [4] => 12, [5] => 13, [6] => 14, [7] => 15,
經過一系列 +
踩坑,可以理解 +
does not append or merge. 使用 +
時,請記得它的 union operator。
與 +
類似的 array function 則是 array_replace()
1 What is the difference between array_merge and array + array in PHP?
2 PHP 文件-Arrays規範
PHP Arrays
Merging two arrays with the "+" (array union operator) How does it work?
array_merge vs array_replace vs + (plus aka union) in PHP