Bacysoft.cn

 找回密码
 邀请注册
查看: 13221|回复: 0
打印 上一主题 下一主题

PHP 文件夹遍历

[复制链接]
跳转到指定楼层
楼主
发表于 2013-3-27 11:03:59 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
在开发PHP应用的过程中,经常会碰到需要遍历某个指定的文件夹,包括这个文件夹下的所有文件和子文件夹!

这里分享一个用 PHP 写的实现文件夹遍历功能的函数,具体代码如下:
  1. function traversal($dir){
  2.         $arr = array();
  3.         $flist = glob($dir);
  4.         foreach($flist as $fn){
  5.                 if(filetype($fn)=='dir'){
  6.                         $arr[] = traversal($fn."/*");
  7.                 }else{
  8.                         $arr[] = $fn;
  9.                 }
  10.         }
  11.         return $arr;
  12. }
复制代码
该函数只实现简单遍历功能,返回值为指定目录的目录结构并保存在数组中,输出如下:
  1. Array
  2. (
  3.     [0] => Array
  4.         (
  5.             [0] => Array
  6.                 (
  7.                     [0] => develop/image/Thumbs.db
  8.                     [1] => develop/image/bg_arrow_up.png
  9.                     [2] => develop/image/bg_dev_hd.png
  10.                     [3] => develop/image/bg_dev_v2.png
  11.                )

  12.             [1] => Array
  13.                 (
  14.                     [0] => develop/include/export.php
  15.                     [1] => develop/include/hooklist.php
  16.                     [2] => develop/include/language.php
  17.                     [3] => develop/include/list.php
  18.                )

  19.             [2] => develop/plugin.lang.php
  20.             [3] => develop/plugin.php
  21.             [4] => Array
  22.                 (
  23.                     [0] => develop/template/ajax.htm
  24.                     [1] => Array
  25.                         (
  26.                             [0] => develop/template/common/developer.css
  27.                             [1] => develop/template/common/footer.htm
  28.                             [2] => develop/template/common/header.htm
  29.                             [3] => develop/template/common/showmessage.htm
  30.                         )

  31.                     [2] => develop/template/common.js
  32.                     [3] => develop/template/language.htm
  33.                )

  34.         )

  35. )
复制代码
如需更复杂的功能,比如:遍历的同时对文件或者子文件夹做对应的操作,只需要在本函数基础上,添加一个处理函数即可。
您需要登录后才可以回帖 登录 | 邀请注册

本版积分规则



京ICP备08000958号-1|腾讯云|阿里云|联系方式|Bacysoft.cn

GMT+8, 2024-4-29 22:27 , Processed in 0.014446 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表