PHP排序文件RecursiveDirectoryIterator

时间:2013-05-23 17:43:57

标签: php sorting recursion spl

我正在使用以下代码列出我子目录中的文件

// Create recursive dir iterator and skip the dot folders
$dir = new RecursiveDirectoryIterator('.',
FilesystemIterator::SKIP_DOTS);

// Folders come before their files
$file  = new RecursiveIteratorIterator($dir,
RecursiveIteratorIterator::SELF_FIRST);

// Maximum depth is 2
$file->setMaxDepth(2);

// Pull out all the xml files that don't contain numbers or special characters
foreach ($file as $fileinfo) {
if ($file->isFile()&& preg_match("/^[a-z]+\.xml/i",$file->getFilename())) {
 $linkname = simplexml_load_file($file->getSubPath().'/'.$file->getFilename());
 echo '<li><a href="'. $file->getSubPath().'/'.$file->getFilename().'">'. $linkname->name .'</a> -' . date('Y-m-d',filemtime($file->getPathName())) . '</li>';
 }
}

我真正想要做的是按照最新修改的日期列出它们,并且能够将返回的文件数量限制为可配置的值。

2 个答案:

答案 0 :(得分:1)

尝试:

// Create recursive dir iterator and skip the dot folders
$dir = new RecursiveDirectoryIterator(".", FilesystemIterator::SKIP_DOTS);

// Folders come before their files
$file = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);

// Maximum depth is 2
$file->setMaxDepth(2);

foreach(new LimitIterator(new SortedFileIterator($file, "xml"), 0, 10) as $fileinfo) {
    printf("%s = %s \n", $fileinfo, date("Y-m-d g:i:s", $fileinfo->getMTime()));
    // Do your stuff
}

一种简单的方法是使用SplHeap

class SortedFileIterator extends SplHeap {
    public function __construct(Iterator $iterator, $ext) {
        foreach($iterator as $item) {
            if ($item->isFile() && $item->getExtension() == $ext) {
                $this->insert($item);
            }
        }
    }
    public function compare($b, $a) {
        return $a->getMTime() == $b->getMTime() ? 0 : ($a->getMTime() > $b->getMTime() ? 1 : - 1);
    }
}

答案 1 :(得分:1)

解决方案SortedFileIterator非常有趣。 SplHeap的插入不会将路径名保留为SplFileInfo的键。

$iteFile = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
foreach($iteFile as $pathname => $cur){
    echo $pathname;
}

使用SortedFileIterator

$iteFile = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
$ite = new SortedFileIterator($itefile,$ext);
foreach($ite as $cur){
    $pathname=$cur->getPathname();
}