View Full Version : Sorting Iterators?

07-12-2007, 07:08 PM
I've had a look around, but can't seem to figure out the best way to, for example, sort the files in a DirectoryIterator. I have code that looks like:

$dirname = '/some/path/to/a/directory';
$files = new DirectoryIterator($dirname);
foreach($files as $file) {
echo $file->getFileName()."\n";

but I'd quite like to sort $files before looping, ideally by providing a callback, as with usort() on arrays. With a collection that I'm creating, the sorting is trivial, but the underlying collection in DirectoryIterator doesn't seem to be accessible- or I haven't been able to find it if it is.
DirectoryIterator and SPLFileObject provide a really nice way to do things with files so it seems a shame to re-implement the functionality just to extend it. Anyone managed to do what I want?

07-12-2007, 07:58 PM
you could use scandir (http://www.php.net/scandir) which takes an order flag as it's second argument

07-13-2007, 02:52 AM
SPL has filterIterators which can be used to filter the results (http://cvs.php.net/viewvc.cgi/php-src/ext/spl/examples/directoryfilterdots.inc?view=markup) but I don't think you will currently be able to sort them (without storing/sorting/iterating again) ... documentation is still sketchy