duanjian7343 2014-12-02 00:56
浏览 66

readdir按文件名排序,其中文件名是月份的名称

<?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条回答 默认 最新

  • doumalu9257 2014-12-02 01:59
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?