PHP array_intersect + array_flip with array that has values multiple times

前端 未结 2 587
青春惊慌失措
青春惊慌失措 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.

提交回复
热议问题