关于php:Array_merge与+

Array_merge versus +

本问题已经有最佳答案,请猛点这里访问。

当我将array_merge()与关联数组一起使用时,我得到了我想要的,但是当我将它们与数字键数组一起使用时,键会发生变化。

使用+时,键被保留,但不适用于关联数组。

我不明白这是怎么回事,有人能给我解释一下吗?


因为这两个数组都有数字索引,所以只使用第一个数组中的值。

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.

http://php.net/manual/en/language.operators.array.php

array_merge()的行为稍有不同:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

http://php.net/manual/en/function.array-merge.php


这两种操作完全不同。

array plus

  • Array plus operation treats all array as assoc array.
  • When key conflict during plus, left(previous) value will be kept
  • null + array() will raise fatal error
  • 数组合并()

  • array_merge() works different with index-array and assoc-array.
  • If both parameters are index-array, array_merge() concat index-array values.
  • If not, the index-array will to convert to values array, and then convert to assoc array.
  • Now it got two assoc array and merge them together, when key conflict, right(last) value will be kept.
  • array_merge(null, array()) returns array() and got a warning said, parameter #1 is not an array.
  • 我发布下面的代码以使事情清楚。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    function array_plus($a, $b){
        $results = array();
        foreach($a as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
        foreach($b as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
        return $results;
    }

    //----------------------------------------------------------------

    function is_index($a){
        $keys = array_keys($a);
        foreach($keys as $key) {
            $i = intval($key);
            if("$key"!="$i") return false;
        }
        return true;
    }

    function array_merge($a, $b){
        if(is_index($a)) $a = array_values($a);
        if(is_index($b)) $b = array_values($b);
        $results = array();
        if(is_index($a) and is_index($b)){
            foreach($a as $v) $results[] = $v;
            foreach($b as $v) $results[] = $v;
        }
        else{
            foreach($a as $k=>$v) $results[$k] = $v;
            foreach($b as $k=>$v) $results[$k] = $v;
        }
        return $results;
    }