scandir() to sort by date modified

这一生的挚爱 提交于 2019-11-26 20:36:44
function scan_dir($dir) {
    $ignored = array('.', '..', '.svn', '.htaccess');

    $files = array();    
    foreach (scandir($dir) as $file) {
        if (in_array($file, $ignored)) continue;
        $files[$file] = filemtime($dir . '/' . $file);
    }

    arsort($files);
    $files = array_keys($files);

    return ($files) ? $files : false;
}

Alternative example..

$dir = "/home/novayear/public_html/backups";
chdir($dir);
array_multisort(array_map('filemtime', ($files = glob("*.{sql,php,7z}", GLOB_BRACE))), SORT_DESC, $files);
foreach($files as $filename)
{
  echo "<a>".substr($filename, 0, -4)."</a><br>"; 
}  

This is a great question and Ryon Sherman’s answer provides a solid answer, but I needed a bit more flexibility for my needs so I created this newer function: better_scandir.

The goal is to allow having scandir sorting order flags work as expected; not just the reverse array sort method in Ryon’s answer. And also explicitly setting SORT_NUMERIC for the array sort since those time values are clearly numbers.

Usage is like this; just switch out SCANDIR_SORT_DESCENDING to SCANDIR_SORT_ASCENDING or even leave it empty for default:

better_scandir(<filepath goes here>, SCANDIR_SORT_DESCENDING);

And here is the function itself:

function better_scandir($dir, $sorting_order = SCANDIR_SORT_ASCENDING) {

  /****************************************************************************/
  // Roll through the scandir values.
  $files = array();
  foreach (scandir($dir, $sorting_order) as $file) {
    if ($file[0] === '.') {
      continue;
    }
    $files[$file] = filemtime($dir . '/' . $file);
  } // foreach

  /****************************************************************************/
  // Sort the files array.
  if ($sorting_order == SCANDIR_SORT_ASCENDING) {
    asort($files, SORT_NUMERIC);
  }
  else {
    arsort($files, SORT_NUMERIC);
  }

  /****************************************************************************/
  // Set the final return value.
  $ret = array_keys($files);

  /****************************************************************************/
  // Return the final value.
  return ($ret) ? $ret : false;

} // better_scandir
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!