array_merge & array_unique

后端 未结 5 731
-上瘾入骨i
-上瘾入骨i 2020-12-11 02:46

Is there an array function in PHP that somehow does array_merge, comparing the values, ignoring the keys? I think that array_unique(array_merge($a, $b

5条回答
  •  北海茫月
    2020-12-11 03:22

    To answer the question as asked, for a general solution that also works with associative arrays while preserving keys, I believe that you will find this solution most satisfactory:

    /**
     * array_merge_unique - return an array of unique values,
     * composed of merging one or more argument array(s).
     *
     * As with array_merge, later keys overwrite earlier keys.
     * Unlike array_merge, however, this rule applies equally to
     * numeric keys, but does not necessarily preserve the original
     * numeric keys.
     */
    function array_merge_unique(array $array1 /* [, array $...] */) {
      $result = array_flip(array_flip($array1));
      foreach (array_slice(func_get_args(),1) as $arg) { 
        $result = 
          array_flip(
            array_flip(
              array_merge($result,$arg)));
      } 
      return $result;
    }
    

提交回复
热议问题