PHP merge arrays with only NOT DUPLICATED values

前端 未结 5 1937
青春惊慌失措
青春惊慌失措 2020-11-29 06:03

I need to merge two arrays into 1 array but what I need is to remove before the main data they b oth have in common (duplicated values i mean), I need only unique values whe

相关标签:
5条回答
  • 2020-11-29 06:44

    If I understand the question correctly:

     $a1 = Array(1,2,3,4);
     $a2 = Array(4,5,6,7);
     $array =  array_diff(array_merge($a1,$a2),array_intersect($a1,$a2));
     print_r($array);
    

    return

    Array
    (
    [0] => 1
    [1] => 2
    [2] => 3
    [5] => 5
    [6] => 6
    [7] => 7
    )
    
    0 讨论(0)
  • 2020-11-29 06:50

    Faster solution:

    function concatArrays($arrays){
        $buf = [];
        foreach($arrays as $arr){
            foreach($arr as $v){
                $buf[$v] = true;
            }
        }
        return array_keys($buf);
    }
    
    
    $array = concatArrays([$array1, $array2]);
    
    0 讨论(0)
  • 2020-11-29 06:56

    I've been running some benchmarks of all the ways I can imagine of doing this. I ran tests on stacking lots of arrays of 10-20 string elements, resulting in one array with all unique strings in there. This sould be about the same for stacking just 2 arrays.

    The fastest I've found was the simplest thing I tried.

    $uniques = [];
    foreach($manyArrays as $arr ) {
      $uniques = array_unique(array_merge($uniques, $arr));
    }
    

    I had branded this 'too naive to work', since it has to sort the uniques array every iteration. However this faster than any other method. Testing with 500.000 elements in manyArrays, each containing 10-20 strings om PHP 7.3.

    A close second is this method, which is about 10% slower.

    $uniques = [];
    foreach($manyArrays as $arr ) {
      foreach($arr as $v) {
        if( !in_array($v, $uniques, false) ) {
          $uniques[] = $v;
        }
      }
    }
    

    The second method could be better in some cases, as this supports the 'strict' parameter of in_array() for strict type checking. Tho if set to true, the second option does become significantly slower than the first (around 40%). The first option does not support strict type checking.

    0 讨论(0)
  • 2020-11-29 07:04

    You can combine the array_merge() function with the array_unique() function (both titles are pretty self-explanatory)

    $array = array_unique (array_merge ($array1, $array2));
    
    0 讨论(0)
  • 2020-11-29 07:04

    A little bit late answer, but I just found that the array union operator + does the job quite greatly (found here at the 3rd section).

    $array1 + $array2 = $array //if duplicate found, the value in $array1 will be considered ($array2 value for array_merge, if keys clearly specified)
    
    0 讨论(0)
提交回复
热议问题