【问题标题】:Using the + operator to combine arrays in PHP在 PHP 中使用 + 运算符组合数组
【发布时间】: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


【解决方案1】:

这是因为上一个示例中的两个数组具有相同的键:

+ 运算符返回附加到左侧数组的右侧数组;对于两个数组中都存在的键,将使用左侧数组中的元素,而忽略右侧数组中的匹配元素。

Docs

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 2020-04-30
    • 2019-12-21
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    相关资源
    最近更新 更多