嗨我有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 \>";
但它不适合我。
答案 0 :(得分:2)
获取数组中的基本文件名列表并对其进行排序
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;
}
);
然后循环数组并显示
答案 1 :(得分:0)
你可以这样做。
//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);
}
);
注意:默认情况下substr_compare区分大小写