php队列方式和递归方式遍历目录文件及子目录

来源:互联网 发布:ssh框架电商项目源码 编辑:程序博客网 时间:2024/05/16 03:20

如果目录很多,推荐队列方式,递归方式会慢,慢的原因:递归的实现是通过调用函数本身,函数调用的时候,每次调用时要做地址保存,参数传递等

[php] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. //递归方式  
  3. function read_dir($dir){  
  4.     $files=array();  
  5.     $dir_list=scandir($dir);  
  6.     foreach($dir_list as $file){  
  7.         if($file!='..' && $file!='.'){  
  8.             if(is_dir($dir.'/'.$file)){  
  9.                 $files[]=read_dir($dir.'/'.$file);  
  10.             }else{  
  11.                 $files[]=$file;  
  12.             }  
  13.         }  
  14.     }  
  15.     return $files;  
  16. }  
  17. //队列方式   
  18. function read_dir_queue($dir){  
  19.     $files=array();  
  20.     $queue=array($dir);  
  21.     while($data=each($queue)){  
  22.         $path=$data['value'];  
  23.         if(is_dir($path) && $handle=opendir($path)){  
  24.             while($file=readdir($handle)){  
  25.                 if($file=='.'||$file=='..'continue;  
  26.                 $files[] = $real_path=$path.'/'.$file;  
  27.                 if (is_dir($real_path)) $queue[] = $real_path;  
  28.             }  
  29.         }  
  30.         closedir($handle);  
  31.     }  
  32.      return $files;  
  33. }  
  34. 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>';
        echo'</tr>';
     }
   }
   echo'</table>';
   closedir($dir_handle);
   echo'在<b>'.$dirname.'</b>目录下的子目录和文件共有<b>'.$num.'</b>个';
?>
0 0