php文件夹遍历的几种方法

函数

function dirTree()
{
    if(!is_dir($path)) return [];
        $files = [];
        $dir = opendir($path);
        while($file = readdir($dir)) {
            if($file == '.' || $file == '..') continue;
            $new_path = trim($path, '/').'/'.trim($file, '/');
            $files[] = $new_path;
            if(is_dir($new_path)){
                $files = array_merge($files, $this->ergodicDir2($new_path));
            }
        }
        closedir($dir);
        return $files;
}

Directory类

function dirTree()
{
    if(!is_dir($path)) return [];
        $files = [];
        $dir_h = dir($path);
        while($file = $dir_h->read()){
            if($file == '.' || $file == '..') continue;
            $new_path = trim($path, '/').'/'.trim($file, '/');
            $files[] = $new_path;
            if(is_dir($new_path)){
                $files = array_merge($files, $this->ergodicDir3($new_path));
            }
        }
        $dir_h->close();
        return $files;
}

迭代器

function dirTree()
{
    if(!is_dir($path)) return [];
    $files = [];
        $dir = new \DirectoryIterator($path);
        foreach ($dir as $key => $file){
            if($file->getFilename() == '.' || $file->getFilename() == '..'){
                continue;
            }
            $files[] = $file->getPathname();
            if($file->isDir()){
                $files = array_merge($files, $this->ergodicDir5($file->getPathname()));
            }
        }
        return $files;
}
function dirTree()
{
    $files = array();
        /**@var \SplFileInfo $file*/
        foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path)) as $file) {
            $filename = $file->getFilename();
            if($filename == '.' || $filename == '..') continue;
            $type = ($file->isDir()) ? '/' : '';
            $files[] = $file->getPathname() . $type;
        }
        return array_unique($files);
}

你可能感兴趣的:(【语言】,----------PHP,【技能加成】,----------小逻辑)