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
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.
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.
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.
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
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With