Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove keys from an array which are not in another array?

Tags:

arrays

php

I have the following two arrays:

EDIT

On suggestion from @Wrikken I've cleaned the first array and now have this:

First Array:

Array
(
    [0] => 3
    [1] => 4
    [2] => 9
    [3] => 11
)

Second Array:

Array
(
    [3] => stdClass Object ( [tid] => 3 )

    [12] => stdClass Object ( tid] => 12 )

    [9] => stdClass Object ( [tid] => 9 )
)

EDIT

The second array is being filtered on the first array. The second array has 3, 12, 9. The first array doesn't contain 12, so 12 should be removed from the second array.

So I should end up with:

Array
(
    [3] => stdClass Object ( [tid] => 3 )

    [9] => stdClass Object ( [tid] => 9 )
)
like image 542
Russell Avatar asked Oct 19 '10 16:10

Russell


2 Answers

You can do this:

$keys = array_map(function($val) { return $val['value']; }, $first);
$result = array_intersect_key(array_flip($keys), $second);

The array_map call will extract the value values from $first so that $keys is an array of these values. Then array_intersect_key is used to get the intersection of $keys (flipped to use the keys as values and vice versa) and the second array $second.

like image 81
Gumbo Avatar answered Oct 20 '22 00:10

Gumbo


After some clean up it was pretty clear what I needed, and this little bit sorts it out:

foreach ($second_array as $foo) {
  if (!in_array($foo->tid, $first_array)) {
    unset($second_array[$foo->tid]);
  }
}   
like image 29
Russell Avatar answered Oct 20 '22 00:10

Russell