php - 不能在 array_filter() 之外调用变量

标签 php arrays array-filter

这个问题在这里已经有了答案:





Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?

(3 个回答)


5年前关闭。




为什么我不能在外部调用变量 array_filter() ,这是我的代码

class JsonSelect
{
    public function jsonSource($jsonSource, $val){

        $file_contents = file_get_contents($jsonSource);

        if(!$file_contents){
            throw new Exception('Invalid file name');
        }

        $json = json_decode($file_contents, true);
        $q = $_POST['q'];
        $filtered = $json;

        if(strlen($q)) {
            $filtered = array_filter($json, function ($key) use ($q) {
                if (stripos($key[$val], $q) !== false) {
                    return true;
                } else {
                    return false;
                }
            });
        }

        echo json_encode(array_slice(array_values($filtered), 0, 20));
    }
}

这是我的图片来描述我的问题。
参数 $val内部无法调用 $key[$val] enter image description here

最佳答案

匿名函数内的变量范围仅在匿名函数内。

您需要从父作用域继承变量。
您可以在关于 anonymous functions 的 PHP 文档中找到有关它的更多详细信息。 (示例#3)

这将改变这条线:

$filtered = array_filter($json, function ($key) use ($q) {

进入这个:
$filtered = array_filter($json, function ($key) use ($q, $val) {

关于php - 不能在 array_filter() 之外调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34922801/

相关文章:

c# - 这个算法的空间复杂度是多少O(1)

javascript - 我试图通过访问嵌套属性并检查它的属性值是否包含特定字符串来过滤数组中的项目

node.js - Mongoose 中的 ArrayFilter

PHP 检查是否有任何数组值不是字符串或数字?

sorting - 如何仅对没有空白单元格的行进行排序?

php - SQLSTATE[42S02] : Base table or view not found - cant find the typo Laravel

php - Memcache + PHP - 为什么数据不会过期?

php - 从管理员内部下订单时被踢出登录屏幕

php - 计算左连接的结果?

arrays - 命名数组的一维