Somewhat simple PHP array intersection question

2019-03-29 06:13发布

问题:

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];
}