开发者

php DirectoryIterator sort files by date

开发者 https://www.devze.com 2023-04-11 01:28 出处:网络
I\'m using php\'s DirectoryIterator class to list files in a directory. I can\'t however figure out an easy way to sort files by date. How is this done with DirectoryIterator

I'm using php's DirectoryIterator class to list files in a directory. I can't however figure out an easy way to sort files by date. How is this done with DirectoryIterator

<?php
 $dir = new DirectoryIterator('.');
  foreach ($dir as $fileinfo) {     
     echo $fileinfo->getFilename() . '<br>';
   }
?>

What if i name my files like whatever_2342345345.ext where the numbers represents time in milliseconds so each file has a unique number. How can we sort by looking at t开发者_JS百科he numbers after underscore


If you need to sort, build an array and sort that.

$files = array();
$dir = new DirectoryIterator('.');
foreach ($dir as $fileinfo) {     
   $files[$fileinfo->getMTime()][] = $fileinfo->getFilename();
}

ksort($files);

This will build an array with the modified time as the key and an array of filenames as the value. It then sorts via ksort(), which will give you the filenames in order of time modified.

If you then want to re-flatten the structure to a standard array, you can use...

$files = call_user_func_array('array_merge', $files);


If you still want to access all the data available at DirectoryIterator (e.g. isDot() getSize() etc) a possible way is to store the Iterator key on the array you are going to sort, and seek the DirectoryIterator later.

$sorted_keys = array();
$dir_iterator = new DirectoryIterator('.');

foreach ( $dir_iterator as $fileinfo )
{
    $sorted_keys[$fileinfo->getMTime()] = $fileinfo->key();
}

ksort($sorted_keys);

/* Iterate `DirectoryIterator` as a sorted array */
foreach ( $sorted_keys as $key ) 
{
    $dir_iterator->seek($key);
    $fileinfo = $dir_iterator->current();

    /* Use $fileinfo here as a normal DirectoryIterator */
    echo $fileinfo->getFilename() . '  ' . $fileinfo->getSize() . '<br>';
}


In case multiple files have the same modified time (updated):

$files = array();
$mtimes = array();
$dir = new DirectoryIterator('.');
foreach($dir as $file){
  if(!$file->isFile())
    continue;

  $mtime = $file->getMTime();

  if(!$mtimes[$mtime]){
    $files[$mtime.'.0'] = $file->getFilename();
    $mtimes[$mtime] = 1;
  }else{
    $files[$mtime.'.'.$mtimes[$mtime]++] = $file->getFilename();
  }
}

ksort($files);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号