0

使用下面的代码,我正在生成位于服务器目录中的 pdf 列表。我想让结果按日期排序,最近的第一个最旧的最后一个。

这是在行动: http: //mt-spacehosting.com/fisheries/plans/northeast-multispecies/

<?php 
$sub = ($_GET['dir']); 
$path = 'groundfish-meetings/';
$path = $path . "$sub"; 
$dh = opendir($path); 
$i=1; 

while (($file = readdir($dh)) !==   false) { 
    if($file != "." && $file != "..") { 
        if (substr($file, -4, -3) =="."){
         echo "$i. <option value='" . home_url('/groundfish-meetings/' . $file) .         "'>$file</option>";
         } $i++; 
        } 
     } closedir($dh); 
?>
</select>

任何帮助,将不胜感激。

4

2 回答 2

1

您可以使用 PHP 的glob函数和自定义排序函数,如下所示:

<?php
$sub = ($_GET['dir']); 
$path = 'groundfish-meetings/';
$path = $path . "$sub";
$file_list = glob($path."*.pdf");

function sort_by_mtime($file1,$file2) {
$time1 = filemtime($file1);
$time2 = filemtime($file2);
if ($time1 == $time2) {
    return 0;
}
return ($time1 < $time2) ? 1 : -1;
}
usort($file_list ,"sort_by_mtime");
$i = 1;
foreach($file_list as $file)
{
  echo "$i. <option value='" . home_url('/groundfish-meetings/' . $file) .            
"'>$file</option>";
  $i++;
}
于 2013-08-06T20:02:31.487 回答
0

这会将 path/to/files 中的所有文件作为一个数组获取,然后按文件的 mtime 对该数组进行排序

$files = glob('path/to/files/*.*');
usort($files, function($a, $b) {
    return filemtime($a) < filemtime($b);
});
于 2013-08-06T20:03:42.177 回答