繁体   English   中英

PHP:递归快速列出文件夹中的所有文件

[英]PHP: List all files in a folder recursively and fast

我正在寻找递归扫描目录以查找所有现有文件和文件夹的最快方法。

例子:

 - images
 -- image1.png
 -- image2.png
 -- thumbnails
 --- thumb1.png
 --- thumb2.png
 - documents
 -- test.pdf

应该返回:

  • 图像/image1.png
  • 图像/image2.png
  • 图像/缩略图/thumb1.png
  • 图像/缩略图/thumb2.png
  • 文件/test.pdf

所以我会开始:

$filesandfolders = @scandir( $path );
foreach ($filesandfolders as $f){
 if(is_dir($f)){
  //this is a folder
 } else {
 //this is a file 
}
}

但这是最快的方法吗?

您可以使用RecursiveDirectoryIterator - 但我怀疑它比简单的递归 function 更快。

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/path/to/folder'));
foreach ($iterator as $file) {
    if ($file->isDir()) continue;
    $path = $file->getPathname();
}

我喜欢这个花哨的 output,有什么想法吗?

function getAllContentOfLocation($loc)
{
    $scandir = scandir($loc);

    $scandir = array_filter($scandir, function ($element) {
        return !preg_match('/^\./', $element);
    });


    if (empty($scandir)) {
        echo '<p style="color:red">        Empty Dir</p>';
    }

    foreach ($scandir as $file) {
        $baseLink = $loc.DIRECTORY_SEPARATOR.$file;

        echo '<ol>';
        if (is_dir($baseLink)) {
            echo '<p style="font-weight:bold;color:blue">'.$file.'</p>';
            getAllContentOfLocation($baseLink);
        } else {
            echo $file.'';
        }
        echo '</ol>';
    }
}
//Call function and set location that you want to scan
getAllContentOfLocation('.');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM