remove only those keys that are not present in another array
I have 2 arrays
$arr1 = array(
'a' => array(some values here),
'b' => array(some more values here),
'c' => array(some m开发者_开发百科ore and more values here)
);
and
$arr2 = array('a','c');
You can see that $arr2 have 2 values (a,c)
I want to keep those keys in $arr1 whose values are present in $arr1 (maintaining key-value association), and want remove all other values that are not in $arr2
so, output will be
$arr1 = array(
'a' => array(some values here),
'c' => array(some more and more values here)
);
How can I achieve this?
To rephrase a bit, you want to find the keys that are present in both arrays, and keep the values from the first array. This happens to be what array_intersect_key
does:
$arr1 = array_intersect_key($arr1, $arr2)
Note: I haven't used this function very often; you might need to change your second array to something like:
$arr2 = array('a' => 1, 'c' => 1);
to ensure that they're treated as keys rather than values.
Incorporating deceze's tip, you could also do
$arr1 = array_intersect_key($arr1, array_flip($arr2))
which wouldn't require changing your second array.
精彩评论