代码之家  ›  专栏  ›  技术社区  ›  Rounin

在PHP中使用+运算符组合数组

  •  1
  • Rounin  · 技术社区  · 4 年前

    我最近发现 + 可用于在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
    )
    
    */
    

    其中一个和其他的不一样。

    为什么最后一个不起作用?

    1 回复  |  直到 4 年前
        1
  •  3
  •   Barthy    4 年前

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

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

    Docs