Jump to content

PHP Date Sort using scandir()


Go to solution Solved by Barand,

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/318021-php-date-sort-using-scandir/
Share on other sites

It apparently is sorting on the file name, not date the file was modified/created:

Array (
[0] => .
[1] => ..
[2] => AdvisorHub M&A Roundup 01-05-2024.docx
[3] => AdvisorHub Wealth Management Outlook 12-28-2023.docx
[4] => LPL Purchases Atria Wealth Feb 2024.docx
[5] => LPL Retention Offers to Atria Brokers.docx
[6] => Merrill loses team amid exodus of firm lifers Jan 2024.docx
[7] => Raymond James hits record assets Jan 2024.docx
)

  • Solution

I don't fancy the chances of sorting your files by the dates embedded in their names.

Instead, get the filenames, get the date of each file, store in array, then sort the dates.


$files = glob("$dir/*.*");
$fdates = [];

foreach ($files as $f) {
    $fdates[basename($f)] = date('Y-m-d',filemtime($f));
}
asort($fdates);

echo '<ul>';
foreach ($fdates as $fn => $dt) {
    echo "<li>$dt &ndash; $fn</li>";
}
echo "</ul>";

Results wil look something like this

image.png.c18a8b0155b2de84d9c289c819600e8b.png

 

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.