tags:

views:

765

answers:

3

Is there a simple way to sort an iterator in PHP (without just pulling it all into an array and sorting that).

The specific example I have is a DirectoryIterator but it would be nice to have a solution general to any iterator.

$dir = new DirectoryIterator('.');
foreach ($dir as $file)
    echo $file->getFilename();

I'd like to be able to sort these by various criteria (filename, size, etc)

+2  A: 

There is no way to do that. An iterator should "iterate" through the list. You have to sort the underlying list to achieve the needed behavior.

By the way, the more complete reference to the SPL is here: http://www.php.net/~helly/php/ext/spl/

andy.gurin
That's what I was afraid of
Greg
A: 

http://www.ruempler.eu/2008/08/09/php-sortingiterator/

Enrico Stahn
The link is dead.
tomp
A: 

You'll have to reduce using iterator_to_array() then uasort(). And, in my performance testing, sufficiently fast.

To your specific example, the most compact way I know using iterators is below:

// get (recursively) files matching a pattern, each file as SplFileInfo object
$matches = new RegexIterator(
               new RecursiveIteratorIterator(
                   new RecursiveDirectoryIterator('/path/to/files/')
               ),
               '/(\.php|\.ini|\.xml)$/i'
            );
 $files = iterator_to_array($matches);

// sort them by name
uasort($files, create_function('$a,$b', 'return strnatcasecmp($a->getFilename(), $b->getFilename());'));
bishop