Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active December 22, 2019 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/f3e4afd02ce4f35c34debe6c79afc17b to your computer and use it in GitHub Desktop.
Save mtvbrianking/f3e4afd02ce4f35c34debe6c79afc17b to your computer and use it in GitHub Desktop.
Read files in directory into array.
<?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