Sorting files with DirectoryIterator

abernier picture abernier · Sep 6, 2009 · Viewed 7.7k times · Source

I'm making a directory listing PHP5 script for lighttpd. In a given directory, I'd like to be able to list direct sub-directories and files (with informations).

After a quick search, DirectoryIterator seems to be my friend:

foreach (new DirectoryIterator('.') as $file)
{
    echo $file->getFilename() . '<br />';
}

but I'd like to be able to sort files by filename, date, mime-types...etc

How to do this (with ArrayObject/ArrayIterator?) ?

Thanks

Answer

Sergey picture Sergey · Jul 4, 2011

Above solution didn't work for me. Here's what I suggest:

class SortableDirectoryIterator implements IteratorAggregate
{

    private $_storage;

    public function __construct($path)
    {
    $this->_storage = new ArrayObject();

    $files = new DirectoryIterator($path);
    foreach ($files as $file) {
        $this->_storage->offsetSet($file->getFilename(), $file->getFileInfo());
    }
    $this->_storage->uksort(
        function ($a, $b) {
            return strcmp($a, $b);
        }
    );
    }

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

}