Skip to content
salathe edited this page Aug 21, 2010 · 1 revision

Preamble

Over the years, many folks have wanted to have the ability to sort their iterators in some order. Various approaches have been discussed and shared with the most common being to use either [[ArrayObject|http://php.net/arrayobject]] or [[ArrayIterator|http://php.net/arrayiterator]] to hold the contents of the iterator and their respective uasort() methods to do the sorting. This can be done very concisely, as demonstrated below.

A basic SortingIterator which extends ArrayIterator

<?php

class SortingIterator extends ArrayIterator
{
    public function __construct(Traversable $iterator, $callback)
    {
        if ( ! is_callable($callback)) {
            throw new InvalidArgumentException(sprintf('Callback must be callable (%s given).', $callback));
        }

        parent::__construct(iterator_to_array($iterator));
        $this->uasort($callback);
    }
}

// Sort alphabetically using PHP's strnatcasecmp function
$it = new SortingIterator(new FilesystemIterator(__DIR__), 'strnatcasecmp');
foreach ($it as $file) {
    echo $file->getPathname() . PHP_EOL;
}

// Re-sort into decreasing file size order
$it->uasort(function($a,$b){ return $b->getSize() - $a->getSize(); });
foreach ($it as $file) {
    printf("%10d %s" . PHP_EOL, $file->getSize(), $file->getPathname());
}

?>

External links