Somewhat simple PHP array intersection question

拜拜、爱过 提交于 2019-12-12 08:09:36

问题


Maybe I'm going insane, but I could have sworn that there was an PHP core function which took two arrays as arguments:

$a = array('1', '3');
$b = array('1'=>'apples', '2'=>'oranges', '3'=>'kiwis');

And performs an intersection where the values from array $a are checked for collisions with the keys in array $b. Returning something like

array('1'=>'apples', '3'=>'kiwis');

Does such a function exist (which I missed in the documentation), or is there a very optimized way to achieve the same thing?


回答1:


try using array_flip {switches keys with their values} and then use array_intersect() on your example :

$c = array_flip($b); // so you have your original b-array
$intersect = array_intersect($a,c);



回答2:


I'm not 100% clear what you want. Do you want to check values from $a against KEYS from $b?

There's a few intersect functions:

http://php.net/manual/en/function.array-intersect.php http://www.php.net/manual/en/function.array-intersect-key.php

But possibly you need:

http://www.php.net/manual/en/function.array-intersect-ukey.php so that you can define your own function for matching keys and/or values.




回答3:


Do a simple foreach to iterate the first array and get the corresponding values from the second array:

$output = array();
foreach ($a as $key) {
    if (array_key_exists($key, $b)) {
        $output[$key] = $b[$key];
    }
}



回答4:


Just a variation of the Gumbo answer, should be more efficient as the tests on the keys are performed just before entering the loop.

$intersection = array_intersect($a, array_keys($b));
$result=array();
foreach ($intersection as $key) {
    $result[$k]=$b[$k];
}


来源:https://stackoverflow.com/questions/1742018/somewhat-simple-php-array-intersection-question

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