Home  >  Article  >  Backend Development  >  php遍历子文件

php遍历子文件

WBOY
WBOYOriginal
2016-06-20 12:57:401058browse

<?phpfunction list_dir($dirpath){     //判断路径最后一个字符是不是"\"    //如果不是 则在路径后加"\"     if($dirpath[strlen($dirpath)-1]!="\\"){$dirpath.="\\";}     static $result_array=array();     //判断给定路径是否是一个目录    if(is_dir($dirpath)){         //打开目录句柄        $handle=opendir($dirpath);        //从目录句柄中读取条目        //读取该目录下的所有文件及文件夹        while($file=readdir($handle)){             if($file=="."||$file==".."){continue;}             //判断读取出来的是否是一个目录            if(is_dir($dirpath.$file)){                               list_dir($dirpath.$file."\\");            }else{                 //将一个或多个单元压入数组的末尾                array_push($result_array,$dirpath.$file);             }         }     closedir($handle);     }     return $result_array; } $path="D:";$array=list_dir($path); foreach($array as $value){     echo $value; echo "<br>"; }?>
]

要是遍历d盘的时候,由于文件太多,会卡在哪里很久
有没有什么优化的方法


回复讨论(解决方案)

减少遍历的范围是唯一优化的方法
使用 glob 不递归或目录迭代器可使速度提高,但也有限

$p = './';$res = glob("$p/*");for($i=0; $i<count($res); $i++) {  if(is_dir($res[$i]))    foreach(glob("{$res[$i]}/*") as $f) $res[] = $f;}print_r($res);
$path = '.';$ite = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path) );$deep = 0;foreach ($ite as $cur) {  $fn = $cur->getBasename();  if($fn == '.' || $fn == '..') continue;  $res[] = $fn;  if(($d=$ite->getDepth()) == $deep);  echo "$d $fn <br>";}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn