How do I remove keys from an array which are not in another array?
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 )
)
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
.
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]);
}
}
Since you want to filter your array (by all keys that are contained in the other array), you may use the array_filter function.
$first = [3,4,9,11];
$second = [ 3 => 'A' , 9 => 'B' , 12 => 'C'];
$clean = array_filter($second, function($key)use($first){
return in_array($key,$first);
},
ARRAY_FILTER_USE_KEY);
// $clean = [ 3 => 'A' , 9 => 'B'];
The ARRAY_FILTER_USE_KEY
constant is the 3rd parameter of the function so that $key
is actually the key of the $second
array in the callback. This can be adjusted:
Flag determining what arguments are sent to callback (3rd argument):
ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value
Default is 0 which will pass value as the only argument to callback instead.
For associative arrays it can be used simple key allow-list filter:
$arr = array('a' => 123, 'b' => 213, 'c' => 321);
$allowed = array('b', 'c');
print_r(array_intersect_key($arr, array_flip($allowed)));
Will return:
Array
(
[b] => 213
[c] => 321
)
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)));
精彩评论