合併或連線陣列
$fruit1 = ['apples', 'pears'];
$fruit2 = ['bananas', 'oranges'];
$all_of_fruits = array_merge($fruit1, $fruit2);
// now value of $all_of_fruits is [0 => 'apples', 1 => 'pears', 2 => 'bananas', 3 => 'oranges']
請注意,array_merge
將更改數字索引,但會覆蓋字串索引
$fruit1 = ['one' => 'apples', 'two' => 'pears'];
$fruit2 = ['one' => 'bananas', 'two' => 'oranges'];
$all_of_fruits = array_merge($fruit1, $fruit2);
// now value of $all_of_fruits is ['one' => 'bananas', 'two' => 'oranges']
如果第一個陣列的值不能重新編號,則 array_merge
會用第二個陣列的值覆蓋第一個陣列的值。
你可以使用+
運算子以第一個陣列的值永遠不會被覆蓋的方式合併兩個陣列,但它不重新編號數字索引,因此你將丟失具有也在第一個陣列中使用的索引的陣列的值。
$fruit1 = ['one' => 'apples', 'two' => 'pears'];
$fruit2 = ['one' => 'bananas', 'two' => 'oranges'];
$all_of_fruits = $fruit1 + $fruit2;
// now value of $all_of_fruits is ['one' => 'apples', 'two' => 'pears']
$fruit1 = ['apples', 'pears'];
$fruit2 = ['bananas', 'oranges'];
$all_of_fruits = $fruit1 + $fruit2;
// now value of $all_of_fruits is [0 => 'apples', 1 => 'pears']