【问题标题】:readdir sort by filename where file name is the name of the monthsreaddir 按文件名排序,其中文件名是月份的名称
【发布时间】:2014-12-02 00:56:53
【问题描述】:
<?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
?>

我希望向专家寻求帮助。这段代码很好用,只是这个站点需要按月列出文件名。它们被命名为:January.pdf、February.pdf 等......并且它们需要按月倒序排列。所以 December.pdf,然后是 November.pdf 等等......我得到:October.pdf November.pdf April.pdf - 离基地很远。任何想法都将不胜感激。

【问题讨论】:

  • 你可以先将它们收集到一个数组中,然后在那里进行排序

标签: php sorting opendir readdir


【解决方案1】:

在第一次迭代期间,计算月份序数并创建一个数组,其中月份保存在键中,文件名保存在值中。

$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;
  }
}

然后,添加排序步骤。

krsort($files);

最后,对排序后的数组进行迭代:

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

【讨论】:

  • 当然,您可以让 PHP 构建月份数组,这将是一个“更懒惰”的解决方案,即 for( $i = 1, $max = 12; $i &lt;= $max ; $i++ ) { $months[] = date( "M" , mktime( 0 , 0 , 0 , $i ) ); }
  • @SharonLevy 我可以比你的代码更快地输入一个月的枚举;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-09
相关资源
最近更新 更多