To compare two arrays while considering duplicate value

后端 未结 4 771
心在旅途
心在旅途 2020-12-20 23:17

i have two arrays

$array1 = array(1, 2,  2, 3);
$array2 = array( 1, 2,  3,4);

and when did :

var_dump(array_diff($array1,         


        
相关标签:
4条回答
  • 2020-12-20 23:49

    While it may be less elegant, the simple way to do this is with a for loop:

    $diff_array = array();
    for ($i = 0; ($i < count($array1)) and ($i < count($array2)); $i++)
    {
       if ($array1[$i] !== $array2[$i]) { $diff_array[$i] = $array1[$i]; }
    }
    
    0 讨论(0)
  • 2020-12-21 00:00

    Try this

    $array1 = array(1, 2, 2, 3, 4, 5, 5, 7);
    $array2 = array(1, 2, 4, 6, 3, 3, 5);
    $diff = array_filter($array1, 
      function ($val) use (&$array2) { 
        $key = array_search($val, $array2);
        if ( $key === false ) return true;
        unset($array2[$key]);
        return false;
      }
    );
    print_r($diff);
    // Array ( [2] => 2 [6] => 5 [7] => 7 )
    
    0 讨论(0)
  • 2020-12-21 00:06

    This will get you the desired result:

    $array1 = array(1, 2,  2, 3);
    $array2 = array( 1, 2,  3,4);
    
    $countArray1 = array_count_values($array1);
    $countArray2 = array_count_values($array2);
    
    foreach($countArray1 as $value=>$count) {
        if($count > 1) $dupArray[] = $value;
    }
    
    foreach($countArray2 as $value=>$count) {
        if($count > 1) $dupArray[] = $value;
    }
    
    print_r($dupArray);
    

    Result

    Array
    (
        [0] => 2
    )

    Explanation

    Using array_count_values will count all the values of an array, which would look like:

    Array
    (
        [1] => 1
        [2] => 2
        [3] => 1
    )
    
    Array
    (
        [1] => 1
        [2] => 1
        [3] => 1
        [4] => 1
    )

    We then iterate through each array_count_values to locate values that occur more than once. This will work when you have more than one set of duplicate values:

    $array1 = array(1, 2,  2, 3);
    $array2 = array( 1, 2,  3, 4, 3);
    

    Result

    Array
    (
        [0] => 2
        [1] => 3
    )
    0 讨论(0)
  • 2020-12-21 00:14

    If you want to count number of duplicate element from same array as well as from multiple arrays, please use below code,

    <?php
        $array1 = array(1,2,2,3,7);
        $array2 = array(1,2,3,4);
        $diff_array = array();
    
        $diff_array1 = array_count_values($array1);
        $diff_array2 = array_count_values($array2);
    
        $a = array_keys($diff_array1);
        $b = array_keys($diff_array2);
    
        for($i=0;$i<count($a);$i++)
        {
            if($a[$i] == $b[$i])
            {
                $x = $a[$i];
                $y = $b[$i];
                $diff_array1[$x] += $diff_array2[$y];
            }
        } 
        $diff_array1=array_diff($diff_array1, array('1'));
        echo '<pre>';
        print_r($diff_array1);
    ?>
    
    0 讨论(0)
提交回复
热议问题