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
715 views
in Technique[技术] by (71.8m points)

sorting - after using $files = new DirectoryIterator() in PHP, how do you sort the items?

We can get the files in a directory in PHP by

$files = new DirectoryIterator() 

after that is there an easy way to sort the items in a particular order for displaying them? thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It doesn't look like there is a way to sort the data within the iterator.

You could place the display data into an intermediary array, with a key of the value you wish to sort by, and call ksort() on the array. This will take two passes over the data however.

$path = ".";
$files = new DirectoryIterator($path);
$files_array = array();

while($files->valid()) {
        // sort key, ie. modified timestamp
        $key = $files->getMTime();
        $data = $files->getFilename();
        $files_array[$key] = $data;
        $files->next();
}
ksort($files_array);
foreach($files_array as $key => $file){
    print $key . " => " . $file . "
";
}

edit:

if you place all of the information that you want to output for the files in the array values, you can simply implode() the array afterwards, instead of looping through the data once again.


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

...