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

。_饼干妹妹 提交于 2019-11-27 08:03:29

问题


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.


回答1:


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 . "\n";
}

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.




回答2:


$files = new DirectoryIterator($path);
$i = 0;
$paths = array();
while($files->valid()) {
    $paths[$i++] = $files->getFileName();
    $files->next();
}
sort($paths)

May be what you are looking for, you can always of course apply the sort function to sort the paths depending on your preference after that.



来源:https://stackoverflow.com/questions/1076881/after-using-files-new-directoryiterator-in-php-how-do-you-sort-the-items

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