萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 遞迴掃描目錄並依副檔名過濾檔案至陣列

單層目錄掃描(glob)

$files = [];
foreach (glob(__DIR__ . '/*.{jpg,png}', GLOB_BRACE) as $file) {
    if (is_file($file)) $files[] = $file;
}
print_r($files);

GLOB_BRACE 讓大括號展開多副檔名,程式碼簡潔高效。

遞迴掃描(RecursiveDirectoryIterator)

function scanImages(string $dir, array $exts = ['jpg','jpeg','png','gif','webp']): array
{
    $result = [];
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
    );

    foreach ($it as $file) {
        if ($file->isFile()) {
            $ext = strtolower($file->getExtension());
            if (in_array($ext, $exts, true)) {
                $result[] = $file->getPathname();
            }
        }
    }
    return $result;
}

$images = scanImages('/var/www/uploads');
print_r($images);

效能比較

方法適用場景記憶體速度
glob()單層、檔案少一次載入全部快
RecursiveIteratorIterator多層、大量檔案迭代器逐個處理穩定
Generator 版本超大目錄、串流處理極低最優

Generator 版本(記憶體友善)

function scanImagesGen(string $dir, array $exts = ['jpg','png']): \Generator
{
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
    );
    foreach ($it as $file) {
        if ($file->isFile() && in_array(strtolower($file->getExtension()), $exts, true)) {
            yield $file->getPathname();
        }
    }
}

foreach (scanImagesGen('/data/photos') as $path) {
    // 逐個處理,不佔滿記憶體
    processImage($path);
}
copyright © 萬盛學電腦網 all rights reserved