Topic: Help me Obi Wan...

Gah! I'm either very tired of just plain stupid. I can't figure this thing out. I have an array $a containing a list of fruits:

$a = array('apples', 'oranges');

I also have an array $b containing a list of fruits and their quantities:

$b = array('apples' => 4, 'bananas' => 2, 'oranges' => 12, 'grapes' => 1);

Now I want to construct a third array $c that is the intersection of $a and $b based on values from $a and keys from $b. I.e. I want to do something like this:

$c = cool_mix_of_php_array_functions($a, $b);

and get: array('apples' => 4, 'oranges' => 12);

Anyone?

"Programming is like sex: one mistake and you have to support it for the rest of your life."

Re: Help me Obi Wan...

YES! Finally :D

It took half an hour, but we got it! Hopefully not too complex:

array_flip(array_intersect(array_flip($b), ($a)));

Array
(
    [apples] => 4
    [oranges] => 12
)

Re: Help me Obi Wan...

I'm afraid not :D

Try setting the same quantity for more than one element. E.g. set bananas to 4.

"Programming is like sex: one mistake and you have to support it for the rest of your life."

Re: Help me Obi Wan...

$c = $b? :D

Re: Help me Obi Wan...

Rickard wrote:

I'm afraid not :D

Try setting the same quantity for more than one element. E.g. set bananas to 4.

Bah! Ruining my nice solution :P

Seems like a hard problem to solve... you can't create the arrays different or something like that instead? Seems like a foreach is the best solution otherwice...

Re: Help me Obi Wan...

Yes, I solved it like this:

$a = array('apples', 'oranges');
$b = array('apples' => 4, 'bananas' => 2, 'oranges' => 12, 'grapes' => 1);

while (list($key, $value) = @each($b))
{
    if (in_array($key, $a))
        $c[$key] = $value;
}
"Programming is like sex: one mistake and you have to support it for the rest of your life."