Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

php DirectoryIterator sort files by date

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 the numbers after underscore

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...