8

我正在为 lighttpd 创建一个列出 PHP5 脚本的目录。在给定的目录中,我希望能够列出直接的子目录和文件(带有信息)。

经过快速搜索,DirectoryIterator似乎是我的朋友:

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

但我希望能够按文件名、日期、mime 类型...等对文件进行排序

如何做到这一点(使用 ArrayObject/ArrayIterator?)?

谢谢

4

2 回答 2

4

上述解决方案对我不起作用。这是我的建议:

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

}
于 2011-07-04T13:52:20.677 回答
2

Philipp W. 在这里发布了一个很好的例子: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();
    }

}
于 2009-09-06T16:58:06.997 回答