使用 + 运算符组合 PHP 中的数组
Using the + operator to combine arrays in PHP
我最近发现 +
可用于组合 PHP 中的数组。
添加关联数组到关联数组:
$array1 = ["The" => "quick", "brown" => "fox"];
$array2 = ["jumps" => "over", "the" => "lazy dog"];
$combinedArray = $array1 + $array2;
/* Gives:
Array
(
[The] => quick
[brown] => fox
[jumps] => over
[the] => lazy dog
)
*/
将关联数组添加到索引数组:
$array1 = ["The", "quick", "brown", "fox"];
$array2 = ["jumps" => "over", "the" => "lazy dog"];
$combinedArray = $array1 + $array2;
/* Gives:
Array
(
[0] => The
[1] => quick
[2] => brown
[3] => fox
[jumps] => over
[the] => lazy dog
)
*/
将索引数组添加到关联数组:
$array1 = ["The" => "quick", "brown" => "fox"];
$array2 = ["jumps", "over", "the", "lazy dog"];
$combinedArray = $array1 + $array2;
/* Gives:
Array
(
[The] => quick
[brown] => fox
[0] => jumps
[1] => over
[2] => the
[3] => lazy dog
)
*/
将索引数组添加到索引数组:
$array1 = ["The", "quick", "brown", "fox"];
$array2 = ["jumps", "over", "the", "lazy dog"];
$combinedArray = $array1 + $array2;
/* Gives:
Array
(
[0] => The
[1] => quick
[2] => brown
[3] => fox
)
*/
其中一个与其他不同。
为什么最后一个不起作用?
发生这种情况是因为上一个示例中的两个数组具有相同的键:
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
我最近发现 +
可用于组合 PHP 中的数组。
添加关联数组到关联数组:
$array1 = ["The" => "quick", "brown" => "fox"];
$array2 = ["jumps" => "over", "the" => "lazy dog"];
$combinedArray = $array1 + $array2;
/* Gives:
Array
(
[The] => quick
[brown] => fox
[jumps] => over
[the] => lazy dog
)
*/
将关联数组添加到索引数组:
$array1 = ["The", "quick", "brown", "fox"];
$array2 = ["jumps" => "over", "the" => "lazy dog"];
$combinedArray = $array1 + $array2;
/* Gives:
Array
(
[0] => The
[1] => quick
[2] => brown
[3] => fox
[jumps] => over
[the] => lazy dog
)
*/
将索引数组添加到关联数组:
$array1 = ["The" => "quick", "brown" => "fox"];
$array2 = ["jumps", "over", "the", "lazy dog"];
$combinedArray = $array1 + $array2;
/* Gives:
Array
(
[The] => quick
[brown] => fox
[0] => jumps
[1] => over
[2] => the
[3] => lazy dog
)
*/
将索引数组添加到索引数组:
$array1 = ["The", "quick", "brown", "fox"];
$array2 = ["jumps", "over", "the", "lazy dog"];
$combinedArray = $array1 + $array2;
/* Gives:
Array
(
[0] => The
[1] => quick
[2] => brown
[3] => fox
)
*/
其中一个与其他不同。
为什么最后一个不起作用?
发生这种情况是因为上一个示例中的两个数组具有相同的键:
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.