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

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

[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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值