php队列方式和递归方式遍历目录文件及子目录
如果目录很多,推荐队列方式,递归方式会慢,慢的原因:递归的实现是通过调用函数本身,函数调用的时候,每次调用时要做地址保存,参数传递等
[php] view plain copy

- <?php
- //递归方式
- function read_dir($dir){
- $files=array();
- $dir_list=scandir($dir);
- foreach($dir_list as $file){
- if($file!=".." && $file!="."){
- if(is_dir($dir."/".$file)){
- $files[]=read_dir($dir."/".$file);
- }else{
- $files[]=$file;
- }
- }
- }
- return $files;
- }
- //队列方式
- function read_dir_queue($dir){
- $files=array();
- $queue=array($dir);
- while($data=each($queue)){
- $path=$data["value"];
- if(is_dir($path) && $handle=opendir($path)){
- while($file=readdir($handle)){
- if($file=="."||$file=="..") continue;
- $files[] = $real_path=$path."/".$file;
- if (is_dir($real_path)) $queue[] = $real_path;
- }
- }
- closedir($handle);
- }
- return $files;
- }
- print_r(read_dir_queue("D:/webroot/suanfa/dir"));exit;
PHP遍历某个目录下的文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php
$num =0; //用来记录目录下的文件个数
$dirname = "LAMP" ; //要遍历的目录名字
$dir_handle =opendir( $dirname );
echo "<table
border="1" align="center" width="960px" cellspacing="0" cellpadding="0">" ;
echo "<caption><h2>目录" . $dirname . "下面的内容</h2></caption>" ;
echo "<tr
align="left" bgcolor="#cccccc">" ;
echo "<th>文件名</th><th>文件大小</th><th>文件类型</th><th>修改时间</th></tr>" ;
while ( $file =readdir( $dir_handle ))
{
if ( $file != "." && $file != ".." )
{
$dirFile = $dirname . "/" . $file ;
if ( $num ++%2==0) //隔行换色
$bgcolor = "#ffffff" ;
else
$bgcolor = "#cccccc" ;
echo "<tr
bgcolor=" . $bgcolor . ">" ;
echo "<td>" . $file . "</td>" ;
echo "<td>" . filesize ( $dirFile ). "</td>" ;
echo "<td>" . filetype ( $dirFile ). "</td>" ;
echo "<td>" . date ( "Y/n/t" , filemtime ( $dirFile )). "</td>" ;
|