Question

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)

Was it helpful?

Solution

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/

OTHER TIPS

For the ones that end up here 5 years later:

If you make the Iterator an extension of ArrayIterator you can use

ArrayIterator::uasort (to sort by value) and ArrayIterator::uksort (to sort by key)

http://php.net/manual/en/arrayiterator.uasort.php

http://php.net/manual/en/arrayiterator.uksort.php

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());'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top