phpsortingrecursionspl

Sort directory listing using RecursiveDirectoryIterator


I'm using RecursiveDirectoryIterator and RecursiveIteratorIterator to build a file listing tree using code like below. I need to the list to be sorted - either directories then files alphabetically, or just alphabetically.

Can anyone tell me how to sort the file list?

$dir_iterator = new RecursiveDirectoryIterator($groupDirectory);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
    // do stuff with $file
}

Solution

  • This is not possible using the Iterator itself. I have seen an extension to the Iterator class somewhere on SO that did sorting but remember hazily to have had trouble with it.

    Maybe the answers to this question help, even though they point away from the Iterator?

    Update: Here is a dupe to your question with some answers - admittedly not many, though!