遍历目录

<?php
/**
 * 遍历目录
 *
 * @param string $dir 目录硬盘路径
 * @param int $level 目录层级(相对于{$dir}参数指定的目录)
 * @return void
 */
function scan_dir($dir, $level = 0)
{
    $separate = str_repeat('┊┈┈', $level);

    $scandir = scandir($dir);
    foreach ($scandir as $file) {
        if ($file == '.' || $file == '..') continue;

        // 输出名称(不管是目录名还是文件名)
        echo "{$separate}{$file}<br>" . PHP_EOL;

        // 如果是目录则递归调用
        $fullpath = "{$dir}/{$file}";
        if (is_dir($fullpath)) scan_dir($fullpath, $level + 1);
    }
}

scan_dir(__DIR__);

Copyright © 2024 码农人生. All Rights Reserved