[英]filter array by key
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' );
}
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. 这很好用,但是由于我有更多要过滤的键,我在想从主函数传递变量的方法:
filterMyArray($key_to_serch)
没有成功,我也尝试了全局变量,但似乎不起作用。
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? 知道要传递该变量吗?
This is where anonymous functions in PHP 5.3 come in handy (note the use of use
): 这是PHP 5.3中的匿名函数派上用场的地方(请注意use的
use
):
private function filterMyArray($key)
{
return array_filter(
$array,
function check($v) use($key) {
return $v['type'] == $key;
}
);
}
private function filterMyArray($key_to_search) {
function check( $v ) {
return $v[$key_to_search] == 'video';
}
return array_filter( $array, 'check' );
}
should work because the inner function has access to the variables in the outer function 应该起作用,因为内部函数可以访问外部函数中的变量
Here's a PHP < 5.3 version using create_function . 这是使用create_function的PHP <5.3版本。
private function filterMyArray( $key)
{
$fn = create_function( '$v', "return $v[$key] == 'video';");
return array_filter( $array, $fn);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.