php - 帮助 PHP array_filter 函数

标签 php array-filter

扫描目录下的文件请看下面的函数(摘自here)

function scandir_only_files($dir) {
   return array_filter(scandir($dir), function ($item) {
       return is_file($dir.DIRECTORY_SEPARATOR.$item);
   });
}

这不起作用,因为 $dir 不在匿名函数的范围内,并且显示为空,导致过滤器每次都返回 FALSE。我将如何重写它?

最佳答案

您必须使用 use 关键字显式声明从父作用域继承的变量:

// use the `$dir` variable from the parent scope
function ($item) use ($dir) {

function scandir_only_files($dir) {
   return array_filter(scandir($dir), function ($item) use ($dir) {
       return is_file($dir.DIRECTORY_SEPARATOR.$item);
   });
}

参见 this example来自匿名函数页面。

Closures may inherit variables from the parent scope. Any such variables must be declared in the function header. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

关于php - 帮助 PHP array_filter 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7380590/

相关文章:

php - 我应该使用 CodeIgniter 的单元测试类还是 PHPUnit/TOAST?

php - 使用 mysql 进行计算,我在计算时遇到了麻烦

PHP 预替换 : "a period with numbers on each side"

php - 按键值php的数组格式

php - 缓慢的 PHP 脚本 - 自动调试和诊断?

javascript - Cordova - http 请求不处理本地 php

php - 过滤掉不包含指定子字符串的数组值

php过滤空数组

php key 未定义,但有 key

php - 如何找到数组末尾与数组开头相同的最大字符序列?