-
-
Save yuri-ellfort/5ae0478b5e938c4eaf8e08dc433824c4 to your computer and use it in GitHub Desktop.
Directory tree array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Creates a tree-structured array of directories and files from a given root folder. | |
* | |
* Gleaned from: http://stackoverflow.com/questions/952263/deep-recursive-array-of-directory-structure-in-php | |
* | |
* @param string $dir | |
* @param string $regex | |
* @param boolean $ignoreEmpty Do not add empty directories to the tree | |
* @return array | |
*/ | |
function dirtree($dir, $regex='', $ignoreEmpty=false) | |
{ | |
if (!$dir instanceof DirectoryIterator) { | |
$dir = new DirectoryIterator((string)$dir); | |
} | |
$dirs = array(); | |
$files = array(); | |
foreach ($dir as $node) { | |
if ($node->isDir() && !$node->isDot()) { | |
$tree = dirtree($node->getPathname(), $regex, $ignoreEmpty); | |
if (!$ignoreEmpty || count($tree)) { | |
$dirs[$node->getFilename()] = $tree; | |
} | |
} elseif ($node->isFile()) { | |
$name = $node->getFilename(); | |
if ('' == $regex || preg_match($regex, $name)) { | |
$files[] = $name; | |
} | |
} | |
} | |
asort($dirs); | |
sort($files); | |
return $dirs + $files; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment