tags:

views:

75

answers:

4

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 )
)
+1  A: 

Use a callback in array_filter

If your first array really looks like that, you might want to alter it in a more usable one-dimensional array, so you use a simple in_array as part of your callback:

$values = array_map('reset',$array);

I only now see that the keys & object-ids are alike:

$result =  array_intersect_key($objectarray,array_flip(array_map('reset',$array)));
Wrikken
Exactly what I've been struggling with. "return $arr['value']" in the callback is what I expected to work.
roosta
+1  A: 

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.

Gumbo
+4  A: 

This should do the trick:

foreach ($firstArray as $item) {
    if (isset($item['value'])) {
        unset($secondArray[$item['value']];
    }
}
xPheRe
From the OPs comments I think this is wrong. If the value is **not** contained in the first array, it should be removed from the second array.
Felix Kling
Sorry, I hadn't read the comments above.
xPheRe
A: 

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