【发布时间】:2021-12-25 10:17:32
【问题描述】:
我最近发现+ 可用于在 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" => "lazy dog"更改为"The" => "lazy dog",看看结果是什么 -
对于最后一个,尝试在两个不同大小的数组(左边一个:4个元素),(右边一个:5个元素)上使用+,看看会发生什么
标签: php arrays associative-array