Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

php - Sort directory listing using RecursiveDirectoryIterator

I'm using RecursiveDirectoryIterator and RecursiveIteratorIterator to build a file listing tree using code like below. I need to the list to be sorted - either directories then files alphabetically, or just alphabetically.

Can anyone tell me how to sort the file list?

$dir_iterator = new RecursiveDirectoryIterator($groupDirectory);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
    // do stuff with $file
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are multiple options available, which you can use to sort an iterator in one way or another. The best option would depend a great deal on precisely how you want to manipulate the iterator contents, what you want to get out of the iterator and indeed how much or little of the iterator you really want/need.

Approaches would vary; making use of classes like SplHeap (or Min, Max varieties), SplPriorityQueue (maybe for things like file size) or just wrapping your iterator in something like ArrayObject which can sort its own contents.

I'll use an SplHeap as an example. Since you want to arrange the entire contents of the RecursiveDirectoryIterator alphabetically then something like the following could be used:

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;
}

The sorting order is alphabetical, mixing files and folders:

./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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...