Home > Backend Development > PHP Tutorial > php遍历子文件,该怎么解决

php遍历子文件,该怎么解决

WBOY
Release: 2016-06-13 12:18:57
Original
1019 people have browsed it

php遍历子文件

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

要是遍历d盘的时候,由于文件太多,会卡在哪里很久
有没有什么优化的方法
------解决思路----------------------
减少遍历的范围是唯一优化的方法
使用 glob 不递归或目录迭代器可使速度提高,但也有限
$p = './';<br />$res = glob("$p/*");<br />for($i=0; $i<count($res); $i++) {<br />  if(is_dir($res[$i]))<br />    foreach(glob("{$res[$i]}/*") as $f) $res[] = $f;<br />}<br />print_r($res);
Copy after login
$path = '.';<br />$ite = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path) );<br /><br />$deep = 0;<br />foreach ($ite as $cur) {<br />  $fn = $cur->getBasename();<br />  if($fn == '.' <br><font color='#FF8000'>------解决思路----------------------</font><br> $fn == '..') continue;<br />  $res[] = $fn;<br />  if(($d=$ite->getDepth()) == $deep);<br />  echo "$d $fn <br>";<br />}
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template