I need help to make it work. I’m using this code for list all json files from folder and paginate it and this works well.
JavaScript
x
<?php
$all_files = [];
$dir = new DirectoryIterator(dirname(__FILE__) . DIRECTORY_SEPARATOR . constant('POSTS_DIR'));
foreach ($dir as $fileinfo) {
if ($fileinfo->isFile() && in_array($fileinfo->getExtension(), array('json'))) {
array_push($all_files, realpath(constant('POSTS_DIR')) . '/' . $fileinfo->getBasename());
}
}
?>
But how can I implement sort by getMTime()
and krsort()
?
I want the last modified files at first.
Advertisement
Answer
Store the mtime values in a separate array, then sort by them with usort
.
Before the loop, add:
JavaScript
$mtimes = [];
In the loop:
JavaScript
$all_files[] = $file = realpath(constant('POSTS_DIR')) . '/' . $fileinfo->getBasename());
$mtimes[$file] = $fileinfo->getMTime();
Then, after the loop:
JavaScript
usort($all_files, function ($a, $b) use ($mtimes) {
return $mtimes[$b] <=> $mtimes[$a];
});