PHP:如何使用array_filter()来过滤数组键? [英] PHP: How to use array_filter() to filter array keys?

查看:889
本文介绍了PHP:如何使用array_filter()来过滤数组键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回调函数array_filter()只传入数组的值,而不是钥匙。

如果我有:

  $ my_array =阵列(富=> 1,你好=>中的世界);$允许=阵列(富,酒吧);

什么是删除 $ my_array 不属于 $允许阵列中的所有键的最好方法是什么?

所需的输出:

  $ my_array =阵列(富=> 1);


解决方案

如果你使用PHP> = 5.6现在可以设置一个标志,对数组的键,而不是数组值过滤:

  $允许= ['富','酒吧'];
$ =过滤array_filter(
    $ my_array,
    功能($键)使用($允许的){
        返回in_array($键,允许$);
    },
    ARRAY_FILTER_USE_KEY
);

显然,这并不像 array_intersect_key($ my_array,array_flip($允许的)) 的,但它确实提供对键,例如在执行一个任意测试的额外的灵活性 $允许可以包含正则表达式模式,而不是简单的字符串。

The callback function in array_filter() only passes in the array's values, not the keys.

If I have:

$my_array = array("foo" => 1, "hello" => "world");

$allowed = array("foo", "bar");

What's the best way to delete all keys in $my_array that are not in the $allowed array?

Desired output:

$my_array = array("foo" => 1);

解决方案

If you're using PHP >= 5.6 you can now set a flag to filter on array key instead of array value:

$allowed = ['foo', 'bar'];
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);

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.

这篇关于PHP:如何使用array_filter()来过滤数组键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆