8

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

Charles
  • 50,943
  • 13
  • 104
  • 142
abernier
  • 27,030
  • 20
  • 83
  • 114

2 Answers2

5

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

}
Sergey
  • 51
  • 1
  • 1
  • Using this `SortableDirectoryIterator` instead of `DirectoryIterator` magically works for me. However some explanation of what it actually does would be nice. Does it simplay sort after filename/path? – Alexander Rutz Aug 11 '22 at 08:27
2

Philipp W. posted a good example here: http://php.oregonstate.edu/manual/en/directoryiterator.isfile.php

function cmpSPLFileInfo( $splFileInfo1, $splFileInfo2 )
{
    return strcmp( $splFileInfo1->getFileName(), $splFileInfo2->getFileName() );
}

class DirList extends RecursiveDirectoryIterator
{
    private $dirArray;

    public function __construct( $p )
    {
        parent::__construct( $p );
        $this->dirArray = new ArrayObject();
        foreach( $this as $item )
        {
            $this->dirArray->append( $item );
        }
        $this->dirArray->uasort( "cmpSPLFileInfo" );
    }

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

}
KiNgMaR
  • 1,557
  • 10
  • 16
  • 1
    The problem I'm finding with this is that it seems to sort everything properly, but the numerical keys remain the same. This seems to make a foreach iterate in the original order, even though a print_r prints everything in the correct order. – enobrev Oct 04 '11 at 14:37
  • *foreach* always follows the order of the array, it doesn't sort by numerical keys. – AndreKR Sep 22 '12 at 12:49
  • change the above code from **uasort()** to **usort()** to reset the keys. – ryanwinchester Mar 26 '13 at 01:34
  • You can't use usort on ArrayObject ( http://php.net/manual/en/class.arrayobject.php ) – Frug Oct 07 '13 at 05:42