首页 > Web开发 > 详细

PHP递归和非递归遍历文件夹下文件

时间:2019-01-01 21:36:11      阅读:164      评论:0      收藏:0      [点我收藏+]

function readDirFiles($dir){
    $files= [];
    $queue=[realpath($dir)];

    $currentPath = current($queue);
    while($currentPath) {
        $path = $currentPath;
        if (is_dir($path) && $handle = opendir($path)) {
            while ($file = readdir($handle)) {
                if ($file == ‘.‘ || $file == ‘..‘) continue;

                $filepath = $path . ‘/‘ . $file;

                if (is_dir($filepath)) {
                    $queue[] = $filepath;
                }else {
                    $files[] = $filepath;
                }
            }

            closedir($handle);
        }

        $currentPath = next($queue);
    }

    return $files;
}

print_r($readDirFiles(‘./‘));exit;

function readDirFiles2($path, &$files = []){
    if (is_dir($path) && $handle = opendir($path)) {
        while ($file = readdir($handle)) {
//            if(strpos($file, ‘.‘) === 0) {
//                continue;
//            }
            if ($file == ‘.‘ || $file == ‘..‘) continue;

            $filePath = $path . ‘/‘ . $file;

            if (is_dir($filePath)) {
                readDirFiles2($filePath, $files);
            }else {
                $files[] = $filePath;
            }
        }

        closedir($handle);
    }

    return $files;
}

readDirFiles2(‘./‘, $paths);
print_r($paths);exit;

PHP递归和非递归遍历文件夹下文件

原文:https://www.cnblogs.com/qixidi/p/10206076.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!