Created
December 1, 2011 10:37
-
-
Save gourneau/1415698 to your computer and use it in GitHub Desktop.
PHP List Directories by Date
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 | |
//This little PHP script is the most elegant way | |
//I could find the list directories and | |
//files with PHP and sort by date | |
//thanks to StackOverflow | |
$files = array(); | |
$dir = new DirectoryIterator('.'); | |
foreach ($dir as $fileinfo) { | |
$files[$fileinfo->getMTime()] = $fileinfo->getFilename(); | |
} | |
//krsort will sort in reverse order | |
krsort($files); | |
//just print out the file names | |
//excluding this file (named index.php and the dir "." ) | |
foreach($files as $file){ | |
if ($file == "index.php" or $file == "." ){ | |
}else{ | |
print $file; | |
print "</br>"; | |
} | |
} | |
?> |
@Pretzel911 You are right.
For anyone else with this problem - simple fix for this is using multidimensional array.
Replace
$files[$fileinfo->getMTime()] = $fileinfo->getFilename();
with
$files[$fileinfo->getMTime()][] = $fileinfo->getFilename();
then we need to somehow flatten this array. I'm using Laravel with this so I have array_flatten helper function available, but with plain PHP it could be done by simple nested foreach like this
$array = []; foreach ($files as $group) { foreach ($group as $item) { $array[] = $item; } }
Not that short and elegant as original gist, but it works...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Testing out how to do this, and noticed a bug. Simply if multiple files have the same modified date, only one get's listed.
ex:
https://imgur.com/a/XKVXlwe
I might be late to the party, it's a good starting point for me either way.