有多种选项可用,您可以使用这些选项以某种方式对迭代器进行排序。最好的选择将取决于你想要如何操作迭代器的内容,你想从迭代器中得到什么,以及你真正想要/需要的迭代器有多少。
方法会有所不同;使用类似SplHeap
(或Min
,Max
变种),SplPriorityQueue
(可能用于文件大小等),或者只是将迭代器封装到可以对其内容进行排序的类似ArrayObject
之类的类中。
我将以SplHeap
为例。既然要安排RecursiveDirectoryIterator
的全部内容按字母顺序排列,然后像下面这样可以用于:
class ExampleSortedIterator extends SplHeap
{
public function __construct(Iterator $iterator)
{
foreach ($iterator as $item) {
$this->insert($item);
}
}
public function compare($b,$a)
{
return strcmp($a->getRealpath(), $b->getRealpath());
}
}
$dit = new RecursiveDirectoryIterator("./path/to/files");
$rit = new RecursiveIteratorIterator($dit);
$sit = new ExampleSortedIterator($rit);
foreach ($sit as $file) {
echo $file->getPathname() . PHP_EOL;
}
的排序顺序是按字母顺序排列,混合文件和文件夹:
./apple
./apple/alpha.txt
./apple/bravo.txt
./apple/charlie.txt
./artichoke.txt
./banana
./banana/aardvark.txt
./banana/bat.txt
./banana/cat.txt
./beans.txt
./carrot.txt
./cherry
./cherry/amy.txt
./cherry/brian.txt
./cherry/charlie.txt
./damson
./damson/xray.txt
./damson/yacht.txt
./damson/zebra.txt
./duck.txt
[在PHP中使用$ files = new DirectoryIterator()之后可能的重复,如何对项目进行排序?](http://stackoverflow.com/questions/1076881/after-using-files-new-directoryiterator-in- php-how-do-you-sort-the-items) – 2010-05-28 15:49:30
[salathe/spl-examples - Sorting Iterators](https://github.com/salathe/spl-examples/wiki/Sorting-Iterators) – hakre 2012-11-25 17:24:15