Last active
December 22, 2019 17:21
-
-
Save mtvbrianking/f3e4afd02ce4f35c34debe6c79afc17b to your computer and use it in GitHub Desktop.
Read files in directory into 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 | |
/** | |
* Get files in directory. | |
* | |
* @link https://www.php.net/manual/en/class.recursivedirectoryiterator.php#111142 Source | |
* | |
* @param string $dir Directory path | |
* | |
* @throws UnexpectedValueException | |
* | |
* @return array | |
*/ | |
function dirTree($dir) | |
{ | |
$rdi = new \RecursiveDirectoryIterator($dir); | |
// $rii = new \RecursiveIteratorIterator($rdi); | |
$rii = new \RecursiveIteratorIterator($rdi, \RecursiveIteratorIterator::CHILD_FIRST); | |
$tree = []; | |
foreach ($rii as $splFileInfo) { | |
$fileName = $splFileInfo->getFilename(); | |
// Skip hidden files and directories. | |
if ($fileName[0] === '.') { | |
continue; | |
} | |
$path = $splFileInfo->isDir() | |
? array($fileName => []) | |
: array($fileName); | |
for ($depth = $rii->getDepth() - 1; $depth >= 0; $depth--) { | |
$path = array($rii->getSubIterator($depth)->current()->getFilename() => $path); | |
} | |
$tree = array_merge_recursive($tree, $path); | |
} | |
return $tree; | |
} | |
$dir = "C:\\xampp\\htdocs\\sample-project\\storage"; | |
$tree = dirTree($dir); | |
echo json_encode($tree); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment