Sorting files with DirectoryIterator

后端 未结 2 500
小鲜肉
小鲜肉 2021-01-05 05:15

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).

Af

相关标签:
2条回答
  • 2021-01-05 06:08

    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();
        }
    
    }
    
    0 讨论(0)
  • 2021-01-05 06:12

    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();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题