-1

I display files and their date of addition on a page. I would like to add a sort by date but I don't know how to do it. Here is a piece of code:

$dir_a2    = 'serv_fic2/Anglais';

$files_a2  = scandir($dir_a2, 1);

$res = '<div class="container">
          <div class="row title">
            <div class="col-md-12">
              <h1>Gestion Documents Formateurs</h1>
            </div>
          </div>
          <div class="row title">';

$res .= '<div class="col-md-6">
            <b>Anglais</b>';

foreach ($files_a as $key => $value) {
  if(!in_array($value,array(".",".."))){

      $res .=   '<br>'.$value.
                '<i> | mis le : '.date ("d.m.y",filemtime('serv_fic/Anglais/'.$value)).'</i>'.
                '<a href="download.php?path=Anglais&file='.$value.'&down=form">
                  <input type="button" value="Telecharger">
                </a>
                <a href="delete_file.php?path=Anglais&file='.$value.'&u_id=Admin&type=Admin&delete=form">
                  <input type="button" value="Supprimer">
                </a>';

  }

}
DevJ
  • 5
  • 3

1 Answers1

0

You can sort the file time by the following code

$files = scandir($dir_a2, 1);
usort($files, function($a,$b) {
  return filemtime($b) - filemtime($a);
});

This is sort DESC, If you want ASC, change

filemtime($b) - filemtime($a)

to

filemtime($a) - filemtime($b)

If you want to filter filetime in a specific range, try this

// Should from _GET or _POST
$from = strtotime('2020/02/10 00:00:01');
$to = strtotime('2021/03/30 00:00:01');

$files = array_filter($files, function($file) use ($from, $to) {
  return $from <=  filemtime($file) && filemtime($file) <= $to;
});

Then usort

Hope this helps!

Van Tho
  • 618
  • 7
  • 20
  • I'm not sure how to integrate this.. But I think it could be interesting – DevJ Mar 22 '20 at 16:11
  • yeah I've tried and it works, but you may want to filter hidden file: https://stackoverflow.com/questions/8532569/exclude-hidden-files-from-scandir – Van Tho Mar 22 '20 at 16:13