PHP array_intersect + array_flip with array that has values multiple times

邮差的信 提交于 2019-12-01 11:26:29

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

array_unique(array_intersect_key($arr1, array_flip($arr2)))

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!