2010-05-28 54 views
13

我使用RecursiveDirectoryIteratorRecursiveIteratorIterator使用下面的代碼構建文件列表樹。我需要對列表進行排序 - 然後將目錄按字母順序排列或按字母順序排列。使用RecursiveDirectoryIterator排序目錄列表​​

誰能告訴我如何排序文件列表?

$dir_iterator = new RecursiveDirectoryIterator($groupDirectory); 
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST); 
foreach ($iterator as $file) { 
    // do stuff with $file 
} 
+0

[在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

+0

[salathe/spl-examples - Sorting Iterators](https://github.com/salathe/spl-examples/wiki/Sorting-Iterators) – hakre 2012-11-25 17:24:15

回答

1

這是不可能使用Iterator本身。我看到在SO上的某個地方對Iterator類進行了擴展,但這個類可以排序,但是記得很慚愧地遇到了麻煩。

也許this question幫助的答案,儘管他們指出了迭代器?

更新Here是一個愚蠢到你的問題與一些答案 - 承認並不多,但!

+0

Dang。我認爲這些迭代器真的會幫助我。謝謝Pekka。 – 2010-05-28 16:06:26

23

有多種選項可用,您可以使用這些選項以某種方式對迭代器進行排序。最好的選擇將取決於你想要如何操作迭代器的內容,你想從迭代器中得到什麼,以及你真正想要/需要的迭代器有多少。

方法會有所不同;使用類似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 
+0

非常感謝你! – eisberg 2011-04-18 20:23:17

0

Sönke Ruempler有很大的解決方案:

class SortingIterator implements IteratorAggregate 
{ 

     private $iterator = null; 

     public function __construct(Traversable $iterator, $callback) 
     { 
       if (!is_callable($callback)) { 
         throw new InvalidArgumentException('Given callback is not callable!'); 
       } 

       $array = iterator_to_array($iterator); 
       usort($array, $callback); 
       $this->iterator = new ArrayIterator($array); 
     } 


     public function getIterator() 
     { 
       return $this->iterator; 
     } 
} 

來源:http://www.ruempler.eu/2008/08/09/php-sortingiterator

+2

當發佈一個鏈接作爲答案時,請包含足夠的內容,答案是有用的,以防鏈接後來中斷。 – 2012-11-08 13:21:10