Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@toniher
Last active May 22, 2018 16:45
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 toniher/acb4f7a9214a680260f0fefbbe63e5a0 to your computer and use it in GitHub Desktop.
Save toniher/acb4f7a9214a680260f0fefbbe63e5a0 to your computer and use it in GitHub Desktop.
Basic recursive iterator for generating a file and directory array
<?php
# Based on https://secure.php.net/manual/en/class.recursivedirectoryiterator.php#111142
# Based on https://stackoverflow.com/questions/834303/startswith-and-endswith-functions-in-php
$hidden = false;
if ( count( $argv ) > 1 ) {
$ritit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($argv[1], RecursiveIteratorIterator::SELF_FIRST) );
$r = array();
foreach ($ritit as $splFileInfo) {
$filename = strval( $splFileInfo->getFilename() );
$proceed = true;
if ( startsWith( $filename, "." ) && ! $hidden ) {
$proceed = false;
}
if ( $proceed ) {
$path = $splFileInfo->isDir()
? array( $filename => array())
: array( $filename );
for ($depth = $ritit->getDepth() - 1; $depth >= 0; $depth--) {
$proceed = true;
$filename = strval( $ritit->getSubIterator($depth)->current()->getFilename() );
if ( startsWith( $filename, "." ) && ! $hidden ) {
$proceed = false;
}
if ( $proceed ) {
$path = array( $filename => $path );
}
}
$r = array_merge_recursive($r, $path);
}
}
print(json_encode( $r ) );
}
function startsWith($haystack, $needle) {
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment