使用允许的键数组按其键过滤数组
array_filter()
中的回调函数 只传入数组的值,而不是键.
The callback function in array_filter()
only passes in the array's values, not the keys.
如果我有:
$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
删除 $my_array
中所有不在 $allowed
数组中的键的最佳方法是什么?
What's the best way to delete all keys in $my_array
that are not in the $allowed
array?
期望的输出:
$my_array = array("foo" => 1);
推荐答案
PHP 5.6 为 array_filter()
引入了第三个参数,flag
,可以设置为 ARRAY_FILTER_USE_KEY
改为按键过滤价值:
PHP 5.6 introduced a third parameter to array_filter()
, flag
, that you can set to ARRAY_FILTER_USE_KEY
to filter by key instead of value:
$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed = ['foo', 'bar'];
$filtered = array_filter(
$my_array,
function ($key) use ($allowed) {
return in_array($key, $allowed);
},
ARRAY_FILTER_USE_KEY
);
由于 PHP 7.4 引入了箭头函数,我们可以让它更简洁:
Since PHP 7.4 introduced arrow functions we can make this more succinct:
$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed = ['foo', 'bar'];
$filtered = array_filter(
$my_array,
fn ($key) => in_array($key, $allowed),
ARRAY_FILTER_USE_KEY
);
显然这不如 array_intersect_key($my_array, array_flip($allowed))
,但它确实提供了对密钥执行任意测试的额外灵活性,例如$allowed
可以包含正则表达式模式而不是纯字符串.
Clearly this isn't as elegant as array_intersect_key($my_array, array_flip($allowed))
, but it does offer the additional flexibility of performing an arbitrary test against the key, e.g. $allowed
could contain regex patterns instead of plain strings.
您也可以使用 ARRAY_FILTER_USE_BOTH
将值和键都传递给您的过滤器函数.这是一个基于第一个的人为示例,但请注意,我不建议以这种方式使用 $allowed
编码过滤规则:
You can also use ARRAY_FILTER_USE_BOTH
to have both the value and the key passed to your filter function. Here's a contrived example based upon the first, but note that I'd not recommend encoding filtering rules using $allowed
this way:
$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];
$allowed = ['foo' => true, 'bar' => true, 'hello' => 'world'];
$filtered = array_filter(
$my_array,
// N.b. it's ($val, $key) not ($key, $val):
fn ($val, $key) => isset($allowed[$key]) && (
$allowed[$key] === true || $allowed[$key] === $val
),
ARRAY_FILTER_USE_BOTH
); // ['foo' => 1, 'bar' => 'baz']
相关文章