How to compare two arrays and remove matching elements from one for the next loop?

前端 未结 5 556
礼貌的吻别
礼貌的吻别 2020-12-09 17:36

How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?

$A = array(1,2,3         


        
相关标签:
5条回答
  • 2020-12-09 17:57

    Dear easy and clean way

    $clean1 = array_diff($array1, $array2); 
    $clean2 = array_diff($array2, $array1); 
    $final_output = array_merge($clean1, $clean2);
    
    0 讨论(0)
  • 2020-12-09 17:58

    Hey, even better solution: array _ uintersect. This let's you compare the arrays as per array_intersect but then it lets you compare the data with a callback function.

    0 讨论(0)
  • 2020-12-09 18:05

    See also array_unique. If you concatenate the two arrays, it will then yank all duplicates.

    0 讨论(0)
  • 2020-12-09 18:07

    Try to this

    $a = array(0=>'a',1=>'x',2=>'c',3=>'y',4=>'w');
    $b = array(1=>'a',6=>'b',2=>'y',3=>'z');
    $c = array_intersect($a, $b);
    
    $result = array_diff($a, $c);
    print_r($result);
    
    0 讨论(0)
  • 2020-12-09 18:22

    You've got it. Just use array_diff or array_intersect. Doesn't get much easier than that.

    Edit: For example:

    $arr_1 = array_diff($arr_1, $arr_2);
    $arr_2 = array_diff($arr_2, $arr_1);
    

    Source

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