$my_array = ["foo" => 1, "hello" => "world"];
$allowed = ["foo", "bar"];
reset($my_array ); // Unnecessary in this case, as we just defined the array, but
// make sure your array is reset (see below for further explanation).
$my_array = array_filter($my_array, function($value) use (&$my_array, $allowed) {
$key = key($my_array); // request key of current internal array pointer
next($my_array); // advance internal array pointer
return isset($allowed[$key]);
});
// $my_array now equals ['foo' => 1]
function filter_array_keys(array $array, $callback)
{
$matchedKeys = array_filter(array_keys($array), $callback);
return array_intersect_key($array, array_flip($matchedKeys));
}
$result = filter_array_keys($my_array, function ($k) use ($allowed) {
return in_array($k, $allowed);
});
< p > < br >
这里是我的一个增强版本,它接受一个回调或直接输入键:
function filter_array_keys(array $array, $keys)
{
if (is_callable($keys)) {
$keys = array_filter(array_keys($array), $keys);
}
return array_intersect_key($array, array_flip($keys));
}
// using a callback, like array_filter:
$result = filter_array_keys($my_array, function ($k) use ($allowed) {
return in_array($k, $allowed);
});
// or, if you already have the keys:
$result = filter_array_keys($my_array, $allowed));
< p > < br >
最后但并非最不重要的,你也可以使用简单的foreach:
$result = [];
foreach ($my_array as $key => $value) {
if (in_array($key, $allowed)) {
$result[$key] = $value;
}
}