Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
1

PHP Date Sort using scandir()

New Here ,
Feb 14, 2024 Feb 14, 2024

I have been racking my brain with this with no obvious solution. For the life of me I cannot sort the following by date. When I run it I get the following output where 2024-02-01 should be before 2024-02-13:

  • 2024-01-30
  • 2024-02-13
  • 2024-02-14
  • 2024-02-01

//PATH

$dirPath    = 'INuploads';
// $dirPath contain path to directory whose files are to be listed 
$files = scandir($dirPath); 
//SORT
usort($files);
//PRINT OUT RESULTS
foreach ($files as $file) {
    $filePath = $dirPath . '/' . $file;
    if (is_file($filePath)) {
        echo "<a href='INuploads/$file' target=new>" . $file . "</a>". date ("Y-m-d", filemtime("$dirPath/$file"));
     }
 
Any suggestions would be greatly appriciated. I have tried many different variotions of this, arsort, sort, ksort
TOPICS
Code
343
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Feb 14, 2024 Feb 14, 2024
LATEST

Does this improve anything:

 

<?php
$dirPath = 'INuploads';
$files = scandir($dirPath);

function sortFilesFunction($a, $b) {
return strtotime($b) - strtotime($a);
}

sort($files, "sortFilesFunction");

foreach($files as $file) {
if (!in_array($file, array(".", ".."))) {
echo "<p><a href='INuploads/$file' target='new'>$file</a></p>";
}
}

?>
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines