-
Notifications
You must be signed in to change notification settings - Fork 5
Sorting Iterators
salathe edited this page Aug 21, 2010
·
1 revision
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.
<?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());
}
?>
- ArrayObject and ArrayIterator in the PHP Manual
- PHP: SortingIterator from Soenke Ruempler
- SortableIterator in the Symfony framework
-
Heap, heap, hooray from Tobias Schlitt describes a more focused approach using an
SplMaxHeap
to retain only the top (or bottom) n items after sorting