2014年04月06日 17:21:16

PHP非递归遍历目录文件

作者: 

之前在PHP目录结构遍历函数中写过一个递归实现遍历目录的方法,现在提供一种递归消除的非递归解法。

  1. /**
  2. *
  3. * 目录非递归遍历
  4. * @author Zjmainstay
  5. * @website http://zjmainstay.cn
  6. * @copyright GPL
  7. * @version 1.0
  8. * @year 2014
  9. * @param $dir 遍历的目录
  10. * @return array
  11. * @example
  12. $dir = './';
  13. $files = scandir_through($dir);
  14. echo '<pre>';
  15. $skipLevel = count(explode('/', $dir));
  16. foreach($files as $file) {
  17. $level = count(explode('/', $file['filePath'])) - $skipLevel;
  18. echo str_repeat('-', $level * 2) . $file['file'] . '&lt;br /&gt;';
  19. }
  20. *
  21. */
  22. function scandir_through($dir) {
  23. if(!is_dir($dir) && is_readable($dir)) return array();
  24. $dir = str_replace('\\', '/', $dir);
  25. $dirPath = $dir;
  26. $files = scandir($dir);
  27. $scanedFiles = array();
  28. $count = 0;
  29. while($file = array_shift($files)) { //从头到尾,每次取出一个文件
  30. //当前目录或上一级目录标记
  31. if($file == '.' || $file == '..') continue;
  32. //回退标记处理
  33. if($file == '...') {
  34. $parts = explode('/', rtrim($dirPath, '/')); //移除路径末尾/然后
  35. array_pop($parts);
  36. $dirPath = implode('/', $parts) . '/'; //回退到上一层
  37. continue; //回退符号,返回
  38. }
  39. $filePath = $dirPath . $file; //文件路径
  40. $scanedFiles[$count]['dir'] = false; //默认不是目录
  41. $scanedFiles[$count]['file'] = $file; //文件名
  42. $scanedFiles[$count]['filePath'] = $filePath; //完整路径
  43. //如果是目录,进入搜索内部文件
  44. if(is_dir($filePath)) {
  45. $dirPath = $filePath . '/'; //记录进入的目录
  46. $scanedFiles[$count]['dir'] = true; //标记为目录
  47. //这里注意理解array_merge的顺序
  48. //scandir($filePath) 得到当前目录内的文件(优先遍历)
  49. //$files是当前目录后面的文件
  50. //php
  51. // file1.txt //scandir('./php')
  52. // file2.txt //scandir('./php')
  53. //... //go back
  54. //js //$files
  55. //使用...作为目录分隔回退符号
  56. $files = array_merge(scandir($filePath), array('...'), $files);
  57. }
  58. $count ++; //文件计数
  59. }
  60. return $scanedFiles;
  61. }

演示:PHP非递归遍历目录文件



未经同意禁止转载!
转载请附带本文原文地址:PHP非递归遍历目录文件,首发自 Zjmainstay学习笔记
阅读( 3875 )
看完顺手点个赞呗:
(2 votes)

1.PHP cURL群:PHP cURL高级技术
2.正则表达式群:专精正则表达式
3. QQ联系(加请说明):QQ联系博主(951086941)
4. 邮箱:zjmainstay@163.com
5. 打赏博主:

网站总访问量: