带参数的 PHP array_filter [英] PHP array_filter with arguments
问题描述
我有以下代码:
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?
推荐答案
作为@Charles 使用闭包的解决方案,你实际上可以找到一个例子 在文档页面的评论 中.这个想法是,您创建一个具有所需状态 ($num
) 和回调方法(以 $i
作为参数)的对象:
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
和诸如 isLower
、isGreater
之类的方法>, isEqual
等等.只是一个想法 —和一个演示...
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屋!