PHP array_intersect + array_flip with array that has values multiple times

前端 未结 2 564
青春惊慌失措
青春惊慌失措 2021-01-14 22:16

I have two arrays:

$arr1 = array(101 => 250, 102 => 250, 103 => 250, 104 => 500, 105 => 500, 106 => 500,);

and

         


        
相关标签:
2条回答
  • 2021-01-14 22:26

    Using the standard php library functions for this might reduce the readability of the code. I would go with an explicit foreach loop that goes over $arr2.

    $ans = array();
    
    foreach($arr2 as $key) {
        if (isset($arr1[$key]) && !in_array($arr1[$key], $ans)) {
            $ans[$key] = $arr1[$key];
        }
    }
    

    This function should O(n*n) where n is the length of $arr2.

    0 讨论(0)
  • 2021-01-14 22:34

    The following code does the job. I hope it is self-explanatory.

    array_unique(array_intersect_key($arr1, array_flip($arr2)))
    
    0 讨论(0)
提交回复
热议问题