有多種選項可用,您可以使用這些選項以某種方式對迭代器進行排序。最好的選擇將取決於你想要如何操作迭代器的內容,你想從迭代器中得到什麼,以及你真正想要/需要的迭代器有多少。
方法會有所不同;使用類似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