Filter array by its keys using an array of allowed keys(使用允许的键数组按其键过滤数组)
问题描述
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']
这篇关于使用允许的键数组按其键过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用允许的键数组按其键过滤数组
基础教程推荐
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01