Merge 2 arrays with no duplicated keys

后端 未结 2 610
逝去的感伤
逝去的感伤 2021-01-21 18:09

I have 2 arrays like below and want to merge them together and not duplicate keys into a new array.

$array1:

Array
(
[0] => Array
    (
        [a] =&         


        
相关标签:
2条回答
  • 2021-01-21 18:22
    function array_merge_recursive_unique($array1, $array2) {
      if (empty($array1)) return $array2; //optimize the base case
    
      foreach ($array2 as $key => $value) {
        if (is_array($value) && is_array(@$array1[$key])) {
          $value = array_merge_recursive_unique($array1[$key], $value);
        }
        $array1[$key] = $value;
      }
      return $array1;
    }
    
    0 讨论(0)
  • 2021-01-21 18:37

    Have you tried user custom examples/functions from the array_merge page? http://php.net/manual/en/function.array-merge.php

    There seem to be quite a few examples that might fit your bill. One suggestion for keeping keys (no renumbering) is to use the + operator

    $result = $x1 + $x2 (where x's are arrays)

    0 讨论(0)
提交回复
热议问题