Skip to content
Advertisement

List all json files from folder then sort by date and paginate it

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.

<?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:

$mtimes = [];

In the loop:

    $all_files[] = $file = realpath(constant('POSTS_DIR')) . '/' . $fileinfo->getBasename());
    $mtimes[$file] = $fileinfo->getMTime();

Then, after the loop:

usort($all_files, function ($a, $b) use ($mtimes) {
    return $mtimes[$b] <=> $mtimes[$a];
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement