Recursively traverse folders into a multidimensional array


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. header('Content-Type: text/plain; charset=utf-8');
  4.  
  5. $dir = dirname(__FILE__).'/';
  6. $tree = dir_tree($dir);
  7. print_r($tree);
  8.  
  9. function dir_tree($dir)
  10. {
  11. static $tree = array();
  12. static $child = false;
  13.  
  14. // Detect the current branch to append files/directories to
  15. if ($child !== false && isset($tree[$child]))
  16. {
  17. $branch =& $tree[$child];
  18. }
  19. else
  20. {
  21. $branch =& $tree;
  22. }
  23.  
  24. // Force trailing slash on directory
  25. $dir = rtrim($dir, '/').'/';
  26. $dirlen = strlen($dir);
  27.  
  28. // Find files/directories
  29. $items = glob($dir.'*');
  30.  
  31. foreach($items as $key => $item)
  32. {
  33. // Get basename
  34. $base = pathinfo($item, PATHINFO_BASENAME); //substr($item, $dirlen);
  35.  
  36. // always skip dot files
  37. if ($base[0] == '.') continue;
  38.  
  39. // If file
  40. if(is_file($item) && is_readable($item))
  41. {
  42. $branch[] = $base;
  43. $child = false;
  44. continue;
  45. }
  46.  
  47. // If directory
  48. if(is_dir($item) && is_readable($item))
  49. {
  50. // Dirty hack to get around PHP's numerical index rules
  51. if (ctype_digit($base))
  52. $base = '~'.$base;
  53.  
  54. $branch[$base] = array();
  55. $child = $base;
  56. dir_tree($item);
  57. continue;
  58. }
  59. }
  60.  
  61. // Only return from the root call
  62. if ($child === false)
  63. return $tree;
  64. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.