Last active
May 22, 2018 16:45
-
-
Save toniher/acb4f7a9214a680260f0fefbbe63e5a0 to your computer and use it in GitHub Desktop.
Basic recursive iterator for generating a file and directory 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 | |
# 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