【问题标题】:How can I use argument of outer function in an inner function in php?如何在php的内部函数中使用外部函数的参数?
【发布时间】:2021-02-25 03:27:38
【问题描述】:

我正在尝试在 php 中使用 array_filter() 构建自定义过滤器功能



    $lst = [["indexNo" => '123', "name" =>"aaa", grade => 8],
    ["indexNo" => '124', "name" =>"abc", grade => 8],
    ["indexNo" => '125', "name" =>"avb", grade => 9]
    ];
    
    function filterByIndex($grade){
            global $lst;
            return array_filter($lst, function($record){
                
                $record['grade'] == $grade;
            });
    
            
        }


编译器说$garde in line($record['grade'] == $grade) 没有声明。

我能为它做些什么?

【问题讨论】:

    标签: php multidimensional-array array-filter


    【解决方案1】:

    三个问题。首先,$grade与函数定义中的$garde不一样。其次,使用use() 构造将变量获取到匿名函数中。第三,你需要returntrue或false过滤器才能工作:

    function filterByIndex($grade){
            global $lst;
            return array_filter($lst, function($record) use($grade){
                return ($record['grade'] == $grade);
            });
    }
    

    此外,在您的 $lst 定义中,您使用的是索引 garde,但在函数中您使用的是索引 grade。

    工作Demo。

    【讨论】:

    • 它对我有用。实际上我不知道 use() 因为我是 php 的初学者。谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多