-4

Hi i have php which shows me all files in dir and make them href. in the output i have list of files like kpi_03.03.2015.html, kpi_02.03.2015.html etc. I need to sort the output by date for example.

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

I tried lot of variants like:

sort($thelist);

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

But its not working for me.

dend
  • 13
  • 1
  • 7
  • Please add your current output and your expected one – Rizier123 Mar 03 '15 at 11:05
  • load the file list to an array and use [usort](http://php.net/manual/en/function.usort.php) to sort the array. You can use the sorted array in your loop. – bansi Mar 03 '15 at 11:07
  • @Rizier123 kpi_03.03.2015.html, kpi_02.03.2015.html, kpi_01.03.2015.html etc i need kpi_01.03.2015.html, kpi_02.03.2015.html, kpi_03.03.2015.html. – dend Mar 03 '15 at 11:09

2 Answers2

2

Get the list of base filenames in an array and sort that

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

then loop the array and display

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

You can do it like this.

//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;

you can filter the array before sorting. like the following

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

Note:substr_compare is case sensitive by default

bansi
  • 55,591
  • 6
  • 41
  • 52