php对列出的文件进行排序


php sort the files listing

嗨,我有php,它显示了dir中的所有文件,并使它们成为href。在输出中,我有kpi_03.03.2015.html、kpi_02.03.2015.html等文件的列表。例如,我需要按日期对输出进行排序。

<html>
    <head>
    <meta http-equiv="Content-Type" content="application/html; charset=utf-8" />
    </head>
    <body>
    <?php
     if ($handle = opendir('/opt/nagios/share/kpi_backup')) {
       while (false !== ($file = readdir($handle)))
          {
              if ($file != "." && $file != "..")
              {
                    $thelist .= '<a href="'.$file.'">'.$file.'</a>';
              }
           }
      closedir($handle);
      }
echo "list of files:<br><br>";
echo $thelist;
    ?>
    </body>
    </html>

我尝试了很多变体,比如:

sort($thelist);
for ($i=0; $i <= 4; $i++) 
    echo $thelist[$i]."<br '>"; 

但它对我不起作用。

获取数组中的基本文件名列表,并对进行排序

usort(
    $thelist
    function ($a, $b) {
        $list($d, $m, $y) = explode('.', trim(sscanf($a, 'kpi_[^h]'), '.'));
        $dateA = $y . $m . $d;
        $list($d, $m, $y) = explode('.', trim(sscanf($b, 'kpi_[^h]'), '.'));
        $dateB = $y . $m . $d;
        return $dateA > $dateB;
    }
);

然后循环数组并显示

您可以这样做。

//Read the file list to array
$thelist = array_diff(scandir('/opt/nagios/share/kpi_backup'), array('..', '.'));
//use usort to sort
usort(
    $thelist,
    function ($a, $b) {
        list($d,$m,$y) = sscanf($a, 'kpi_%d.%d.%d');
        $da = sprintf("%d%02d%02d",$y,$m,$d);
        list($d,$m,$y) = sscanf($b, 'kpi_%d.%d.%d');
        $db = sprintf("%d%02d%02d",$y,$m,$d);
        return $da>$db;
    }
);
$print_list='';
foreach($thelist as $file){
    $print_list .= "<a href='"$file'">$file</a>";
}
echo $print_list;

您可以在排序之前对数组进行筛选。像下面的

$thelist=array_filter(
    $thelist,
    function($k){
        return !substr_compare($k,'.html',-5);
    }
);

注意:substra_compare默认情况下区分大小写