PHP 5.2:具有多个参数性能的过滤器数组 [英] PHP 5.2: Filter array with multiple arguments performance
本文介绍了PHP 5.2:具有多个参数性能的过滤器数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码来过滤多维数组:
I'm using this code to filter a multidimensional array:
$sourceArray = array(
array('name'=>'banana', 'color'=>'green'),
array('name'=>'banana', 'color'=>'black'),
array('name'=>'banana', 'color'=>'yelow'),
);
$arrayToCompare = array('type'=>'fruits','has_name'=>'banana', 'has_color'=>'yelow');
$filtered = array();
foreach($sourceArray as $item) {
if($item['name'] !== $arrayToCompare['has_name']) continue;
if($item['color'] !== $arrayToCompare['has_color']) continue;
$filtered[] = $item;
}
但我认为可能存在有效/快速的解决方案。
But I think there might be an efficient/quicker solution.
在PHP 5.3中,我们可以在本机 filter_array(),但在5.2中不受支持:
In PHP 5.3 we can use anonymous functions (closures) inside the native filter_array() but they are not supported in 5.2:
$filtered = array_filter(
$masterItems,
function ($arr) use ($arrayToCompare) { // PHP 5.3 is required here!!
return ($arr['name'] == $arrayToCompare['has_name']
AND $arr['color'] == $arrayToCompare['has_color']);
}
);
在速度方面还有更好的方法吗?
Are there any better approaches in term of speed?
推荐答案
PHP 5.2在 array_filter
函数中接受回调的名称。
PHP 5.2 accepts the name of a callback in the array_filter
function.
function filter($arr)
{
$arrayToCompare = array('type'=>'fruits','has_name'=>'banana', 'has_color'=>'yelow');
return $arr['name'] == $arrayToCompare['has_name']
&& $arr['color'] == $arrayToCompare['has_color'];
}
$filtered = array_filter($masterItems, 'filter');
这篇关于PHP 5.2:具有多个参数性能的过滤器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文