I currently have a script which allows me to output the list of files inside the same directory.
The output shows the names, and then I used filemtime()
function to show the date when the file was modified.
How will I sort the output to show the latest modified file?
This is what I have for now:
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$lastModified = date('F d Y, H:i:s', filemtime($file));
if(strlen($file)-strpos($file, ".swf") == 4) {
echo "$file - $lastModified";
}
}
}
closedir($handle);
}
Once this is set up, you can simply call sort() and the algorithm will compare by the mod times first, then break ties using the unique filenames. $result = []; foreach (glob('path/to/files/*. swf') as $file) { $result[] = [filemtime($file), $file]; } sort($result); var_export($result);
This would get all files in path/to/files with an .swf extension into an array and then sort that array by the file's mtime
$files = glob('path/to/files/*.swf');
usort($files, function($a, $b) {
return filemtime($b) - filemtime($a);
});
The above uses an Lambda function and requires PHP 5.3. Prior to 5.3, you would do
usort($files, create_function('$a,$b', 'return filemtime($b)-filemtime($a);'));
If you don't want to use an anonymous function, you can just as well define the callback as a regular function and pass the function name to usort
instead.
With the resulting array, you would then iterate over the files like this:
foreach($files as $file){
printf('<tr><td><input type="checkbox" name="box[]"></td>
<td><a href="%1$s" target="_blank">%1$s</a></td>
<td>%2$s</td></tr>',
$file, // or basename($file) for just the filename w\out path
date('F d Y, H:i:s', filemtime($file)));
}
Note that because you already called filemtime
when sorting the files, there is no additional cost when calling it again in the foreach loop due to the stat cache.
You need to put the files into an array in order to sort and find the last modified file.
$files = array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort
ksort($files);
// find the last modification
$reallyLastModified = end($files);
foreach($files as $file) {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
if ($file == $reallyLastModified) {
// do stuff for the real last modified file
}
echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}
Not tested, but that's how to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With