$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']