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

// 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>';
 }
}

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

4

2 回答 2

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);
    }
}
于 2013-05-23T18:08:54.917 回答
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();
}
于 2017-03-24T17:17:16.847 回答