PHP array_filter带参数 [英] PHP array_filter with arguments
问题描述
我有以下的code:
function lower_than_10($i) {
return ($i < 10);
}
这是我可以用它来过滤数组是这样的:
that I can use to filter an array like this:
$arr = array(7, 8, 9, 10, 11, 12, 13);
$new_arr = array_filter($arr, 'lower_than_10');
我如何添加参数lower_than_10以便它也接受对证多少?就像,如果我有这样的:
How can I add arguments to lower_than_10 so that it also accepts the number to check against? Like, if I have this:
function lower_than($i, $num) {
return ($i < $num);
}
如何从调用array_filter经过10至$ NUM或什么号码?
how to call it from array_filter passing 10 to $num or whatever number?
推荐答案
作为替代@查尔斯的<一个href=\"http://stackoverflow.com/questions/5482989/php-array-filter-with-arguments/5483102#5483102\">solution使用闭包,实际上你可以发现在评论为例文档页面上。 的想法是,你创建所需的状态( $ NUM
)和回调方法(以 $ I $ C对象$ C>作为参数):
As an alternative to @Charles's solution using closures, you can actually find an example in the comments on the documentation page. The idea is that you create an object with the desired state ($num
) and the callback method (taking $i
as an argument):
class LowerThanFilter {
private $num;
function __construct($num) {
$this->num = $num;
}
function isLower($i) {
return $i < $this->num;
}
}
使用(演示):
$arr = array(7, 8, 9, 10, 11, 12, 13);
$matches = array_filter($arr, array(new LowerThanFilter(12), 'isLower'));
print_r($matches);
一点题外话,你现在可以替换 LowerThanFilter
有一个更通用 NumericComparisonFilter
像<$ C $方法C> islower判断, isGreater
,的isEqual
等只是一个想法&MDASH;和演示 ...
As a sidenote, you can now replace LowerThanFilter
with a more generic NumericComparisonFilter
with methods like isLower
, isGreater
, isEqual
etc. Just a thought — and a demo...
这篇关于PHP array_filter带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!