Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting files with DirectoryIterator

Tags:

php

spl

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

like image 337
abernier Avatar asked Sep 06 '09 16:09

abernier


People also ask

How to change the sort order of files in dir command?

By default DIR command displays the files or folders by sort order in ascending order by name of the files or folders. Below commands produce the same result. How to change this sort order? You need to prefix the symbol “-” before the parameters to reverse the sort order.

How do I sort my files and folders?

There are over 300 criteria available, and you can apply whichever you prefer. By default, in Windows 10, your files and folders are sorted in Ascending order by Name - or alphabetically - except for the Downloads folder, which is sorted in Descending order by Date modified - newest downloads are displayed on top.

How to change sort order of files or folders in Linux?

By default DIR command displays the files or folders by sort order in ascending order by name of the files or folders. Below commands produce the same result. C:\> dir. and. C:\> dir /on. How to change this sort order? You need to prefix the symbol “-” before the parameters to reverse the sort order.

How do I check if a directory iterator is a regular file?

DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file Determines if the current DirectoryIterator item is a regular file. This function has no parameters. Returns true if the file exists and is a regular file (not a link or dir ), otherwise false


1 Answers

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

}
like image 122
Sergey Avatar answered Oct 08 '22 23:10

Sergey