簡體   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