readdir sort by filename where file name is the name of the months

501 Views Asked by At
<?php
$current_dir = "/members/downloads/board-meetings/2014/";    // Full path to directory
$dir = opendir($current_dir);        // Open directory

echo ("");
while ($file = readdir($dir))            // while loop
{
$parts = explode(".", $file);                    // Pull apart the name and     dissect     by     period
if (is_array($parts) && count($parts) > 1) {    
    $extension = end($parts);        // Set to see last file extension

    if ($extension == "pdf" OR $extension == "PDF")    // PDF DOCS by extention
         echo "<li class=\"pdf\"><strong><a href=\"/members/downloads/board-meetings    /$file\" class=\"underline\" target=\"_blank\">$file</a></strong></li>";    //     If so, echo it out!           
    }
}
echo "<br>";
closedir($dir);    // Close the directory
?>

I was hoping to ask for some help from an Expert. This code works great except that this site needs to list the filenames by month. They are named like: January.pdf, February.pdf etc... And they need to be listed in reverse monthly order. So December.pdf, then November.pdf etc... And I get: October.pdf November.pdf April.pdf - way off base. Any ideas would be extremely appreciated.

1

There are 1 best solutions below

2
On

During the first iteration, calculate the month ordinal number and create an array whereby the month is kept in the keys and the file name in the values.

$current_dir = "/members/downloads/board-meetings/2014/";    // Full path to directory
$months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
$dir = opendir($current_dir);        // Open directory
$files = array();

while ($file = readdir($dir)) {
  $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  $month = array_search(substr($file, 0, 3), $months);

  if ($extension == 'pdf') {
    $files[$month] = $file;
  }
}

Then, you add the sorting step.

krsort($files);

Finally, iterate the sorted array:

foreach ($files as $file) {
  echo "<li class=\"pdf\"><strong><a href=\"/members/downloads/board-meetings    /$file\" class=\"underline\" target=\"_blank\">$file</a></strong></li>";    //     If so, echo it out!           
}

echo "<br>";
closedir($dir);    // Close the directory