按键过滤数组 [英] filter array by key

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

问题描述

我有这个小功能可以通过键过滤数组:

I have this little function to filter my array by keys:

 private function filterMyArray( )
 {
      function check( $v )
      {
           return $v['type'] == 'video';
      }
      return array_filter( $array, 'check' );
 }

这很好用,但是由于我有更多要过滤的键,我在考虑一种从主要函数传递变量的方法: filterMyArray($ key_to_serch)没有成功,我也尝试过使用全局变量,但似乎不起作用。

This works great but since I have more keys to filter, I was thinking in a way to pass a variable from the main function: filterMyArray($key_to_serch) without success, also I've tried a global variable, but seems not work.

由于我的问题有些困惑:),我需要这样的东西:

Due some confusion in my question :), I need something like this:

 private function filterMyArray( $key_to_serch )
 {
      function check( $v )
      {
           return $v['type'] == $key_to_serch;
      }
      return array_filter( $array, 'check' );
 }

是否有通过该变量的想法?

Any idea to pass that variable?

推荐答案

这是 PHP 5.3 中的匿名函数派上用场的地方(请注意使用 use ):

This is where anonymous functions in PHP 5.3 come in handy (note the use of use):

private function filterMyArray($key)
{
     return array_filter(
         $array,
         function check($v) use($key) {
             return $v['type'] == $key;
         }
     );
}

这篇关于按键过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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