Keep Duplicates while Using array_diff

后端 未结 2 1707
北荒
北荒 2020-11-29 10:20

I am using array_diff() to take values out of array1 which are found in array2. The issue is it removes all occurrences from array1, as the PHP documentations makes note of.

2条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 11:04

    Write some function that removes elements from first array one by one, something like:

    function array_diff_once($array1, $array2) {
        foreach($array2 as $a) {
            $pos = array_search($a, $array1);
            if($pos !== false) {
                unset($array1[$pos]);
            }
        }
    
        return $array1;
    }
    
    $a = array('a', 'b', 'a', 'c', 'a', 'b');
    $b = array('a', 'b', 'c');
    
    print_r( array_diff_once($a, $b) );
    

提交回复
热议问题