/**** 目录非递归遍历* @author Zjmainstay* @website http://zjmainstay.cn* @copyright GPL* @version 1.0* @year 2014* @param $dir 遍历的目录* @return array* @example$dir = './';$files = scandir_through($dir);echo '<pre>';$skipLevel = count(explode('/', $dir));foreach($files as $file) {$level = count(explode('/', $file['filePath'])) - $skipLevel;echo str_repeat('-', $level * 2) . $file['file'] . '<br />';}**/function scandir_through($dir) {if(!is_dir($dir) && is_readable($dir)) return array();$dir = str_replace('\\', '/', $dir);$dirPath = $dir;$files = scandir($dir);$scanedFiles = array();$count = 0;while($file = array_shift($files)) { //从头到尾,每次取出一个文件//当前目录或上一级目录标记if($file == '.' || $file == '..') continue;//回退标记处理if($file == '...') {$parts = explode('/', rtrim($dirPath, '/')); //移除路径末尾/然后array_pop($parts);$dirPath = implode('/', $parts) . '/'; //回退到上一层continue; //回退符号,返回}$filePath = $dirPath . $file; //文件路径$scanedFiles[$count]['dir'] = false; //默认不是目录$scanedFiles[$count]['file'] = $file; //文件名$scanedFiles[$count]['filePath'] = $filePath; //完整路径//如果是目录,进入搜索内部文件if(is_dir($filePath)) {$dirPath = $filePath . '/'; //记录进入的目录$scanedFiles[$count]['dir'] = true; //标记为目录//这里注意理解array_merge的顺序//scandir($filePath) 得到当前目录内的文件(优先遍历)//$files是当前目录后面的文件//php// file1.txt //scandir('./php')// file2.txt //scandir('./php')//... //go back//js //$files//使用...作为目录分隔回退符号$files = array_merge(scandir($filePath), array('...'), $files);}$count ++; //文件计数}return $scanedFiles;}
演示:PHP非递归遍历目录文件
未经同意禁止转载!
转载请附带本文原文地址:PHP非递归遍历目录文件,首发自 Zjmainstay学习笔记




