PHP array_filter 带参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5482989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:34:53  来源:igfitidea点击:

PHP array_filter with arguments

phparrays

提问by pistacchio

I have the following 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');

How can I add arguments to lower_than_10 so that it also accepts the number to check against? Like, if I have this:

如何将参数添加到 lower_than_10 以便它也接受要检查的数字?就像,如果我有这个:

function lower_than($i, $num) {
    return ($i < $num);
}

how to call it from array_filter passing 10 to $num or whatever number?

如何从 array_filter 调用它,将 10 传递给 $num 或任何数字?

采纳答案by jensgram

As an alternative to @Charles's solution using closures, you can actually find an example in the commentson the documentation page. The idea is that you create an object with the desired state ($num) and the callback method (taking $ias an argument):

作为使用闭包的@Charles 解决方案的替代方案,您实际上可以在文档页面的评论中找到一个示例。这个想法是您创建一个具有所需状态 ( $num) 和回调方法($i作为参数)的对象:

class LowerThanFilter {
        private $num;

        function __construct($num) {
                $this->num = $num;
        }

        function isLower($i) {
                return $i < $this->num;
        }
}

Usage (demo):

用法(演示):

$arr = array(7, 8, 9, 10, 11, 12, 13);
$matches = array_filter($arr, array(new LowerThanFilter(12), 'isLower'));
print_r($matches);


As a sidenote, you can now replace LowerThanFilterwith a more generic NumericComparisonFilterwith methods like isLower, isGreater, isEqualetc. Just a thought — and a demo...

作为一个旁注,你现在可以更换LowerThanFilter一个更通用的NumericComparisonFilter用类似的方法isLowerisGreaterisEqual等只是一个想法-和演示...

回答by ZHENJiNG LiANG

if you a using php 5.3 and above, you can use closureto simplify your code:

如果您使用 php 5.3 及更高版本,则可以使用闭包来简化代码:

$NUM = 5;
$items = array(1, 4, 5, 8, 0, 6);
$filteredItems = array_filter($items, function($elem) use($NUM){
    return $elem < $NUM;
});

回答by Charles

In PHP 5.3 or better, you can use a closure:

在 PHP 5.3 或更高版本中,您可以使用闭包

function create_lower_than($number = 10) {
// The "use" here binds $number to the function at declare time.
// This means that whenever $number appears inside the anonymous
// function, it will have the value it had when the anonymous
// function was declared.
    return function($test) use($number) { return $test < $number; };
}

// We created this with a ten by default.  Let's test.
$lt_10 = create_lower_than();
var_dump($lt_10(9)); // True
var_dump($lt_10(10)); // False
var_dump($lt_10(11)); // False

// Let's try a specific value.
$lt_15 = create_lower_than(15);
var_dump($lt_15(13)); // True
var_dump($lt_15(14)); // True
var_dump($lt_15(15)); // False
var_dump($lt_15(16)); // False

// The creation of the less-than-15 hasn't disrupted our less-than-10:
var_dump($lt_10(9)); // Still true
var_dump($lt_10(10)); // Still false
var_dump($lt_10(11)); // Still false

// We can simply pass the anonymous function anywhere that a
// 'callback' PHP type is expected, such as in array_filter:
$arr = array(7, 8, 9, 10, 11, 12, 13);
$new_arr = array_filter($arr, $lt_10);
print_r($new_arr);

回答by Mar Bar

if you need multiple parameters to be passed to the function, you may append them to the use statement using ",":

如果需要将多个参数传递给函数,可以使用“,”将它们附加到 use 语句中:

$r = array_filter($anArray, function($anElement) use ($a, $b, $c){
    //function body where you may use $anElement, $a, $b and $c
});

回答by Stefan Gehrig

In extension to jensgramanswer you can add some more magic by using the __invoke()magic method.

作为jensgram答案的扩展,您可以使用__invoke()魔术方法添加更多魔术。

class LowerThanFilter {
    private $num;

    public function __construct($num) {
        $this->num = $num;
    }

    public function isLower($i) {
        return $i < $this->num;
    }

    function __invoke($i) {
        return $this->isLower($i);
    }
}

This will allow you to do

这将允许你做

$arr = array(7, 8, 9, 10, 11, 12, 13);
$matches = array_filter($arr, new LowerThanFilter(12));
print_r($matches);

回答by Marcos Basualdo

class ArraySearcher{

const OPERATOR_EQUALS = '==';
const OPERATOR_GREATERTHAN = '>';
const OPERATOR_LOWERTHAN = '<'; 
const OPERATOR_NOT = '!=';      

private $_field;
private $_operation;
private $_val;

public function __construct($field,$operation,$num) {
    $this->_field = $field;
    $this->_operation = $operation;
    $this->_val = $num;
}


function __invoke($i) {
    switch($this->_operation){
        case '==':
            return $i[$this->_field] == $this->_val;
        break;

        case '>':
            return $i[$this->_field] > $this->_val;
        break;

        case '<':
            return $i[$this->_field] < $this->_val;
        break;

        case '!=':
            return $i[$this->_field] != $this->_val;
        break;
    }
}


}

This allows you to filter items in multidimensional arrays:

这允许您过滤多维数组中的项目:

$users = array();
$users[] = array('email' => '[email protected]','name' => 'Robert');
$users[] = array('email' => '[email protected]','name' => 'Carl');
$users[] = array('email' => '[email protected]','name' => 'Robert');

//Print all users called 'Robert'
print_r( array_filter($users, new ArraySearcher('name',ArraySearcher::OPERATOR_EQUALS,'Robert')) );