php - 如何递归遍历PHP中的文件?

标签 php loops

我已经设置了一个基本脚本,它发布了一组路径以在其中查找模板文件;目前它只搜索两层深度,我在理解一个广泛的循环以迭代所有子目录直到长度为 0 的逻辑时遇到了一些麻烦。

所以如果我有这样的结构:

./components
./components/template.html
./components/template2.html
./components/side/template.html
./components/side/template2.html
./components/side/second/template.html
./components/side/second/template2.html
./components/side/second/third/template.html
./components/side/second/third/template2.html

理想情况下,当我希望它检查所有子目录和传递的目录中的 .html 文件时,它只会在“side”目录中搜索 .html 文件。到目前为止,这是我的工作代码:

<?php
function getFiles($path){
    $dh  = opendir($path);
    foreach(glob($path.'/*.html') as $filename){
        $files[] = $filename;
    }
    if (isset($files)) {
        return $files;
    }
}
foreach ($_POST as $path) {
    foreach (glob($path . '/*' , GLOB_ONLYDIR) as $secondLevel) {
        $files[] = getFiles($secondLevel);
    }
    $files[] = getFiles($path);
}
sort($files);
print_r(json_encode($files));
?>

最佳答案

PHP 内置了适合您的完美解决方案。

示例

// Construct the iterator
$it = new RecursiveDirectoryIterator("/components");

// Loop through files
foreach(new RecursiveIteratorIterator($it) as $file) {
    if ($file->getExtension() == 'html') {
        echo $file;
    }
}

资源

关于php - 如何递归遍历PHP中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25909820/

相关文章:

php - 如何将参数从 Controller 传递到 YII2 中的布局

C 问题:另一个 while 循环内的 while(fgets) 循环仅执行一次

C - 一个循环来查找大小数值

JavaScript 函数有效……但不在 for 循环中

PHP比较两个值?

PHP - 从模型加载数据库对象但只有一个实例的最佳方法?

php - 如何通过 htaccess 自定义 401 未经授权页面

javascript - HTML 数据列表中的动态数组

java - 为什么我的 XML 解析器只返回一个字符串,而不是多个字符串?

python - 如何使用字典而不是大量 if/else 语句在 Python 中创建测验?