Last active
July 15, 2022 10:26
-
-
Save jasonhofer/2368606 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 array_merge($dirs, $files); | |
} |
I have a big folders and files structure. Returns only 2 files without folders. $dir was like this: '/home/nick/project'.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If the directory name contains only numbers (for example, year), array_merge() will renumber the array, which is why the function will return an incorrect directory structure.