[英]PHP Sorting Files RecursiveDirectoryIterator
I'm listing the files in my subdirectory just fine using the following code 我使用下面的代码很好地列出了子目录中的文件
// 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>';
}
}
What I would really like it to do is list them by date modified newest first and be able to limit the number of files returned to a configurable value. 我真正希望它执行的操作是按照最新的日期将它们列出,然后将返回的文件数限制为可配置的值。
Try: 尝试:
// 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
}
A simple way is using SplHeap
一种简单的方法是使用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);
}
}
The solution SortedFileIterator is very interesting. 解决方案SortedFileIterator非常有趣。 The insert of SplHeap don't preserve the pathname as key of the SplFileInfo. SplHeap的插入不会将路径名保留为SplFileInfo的键。
$iteFile = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
foreach($iteFile as $pathname => $cur){
echo $pathname;
}
with SortedFileIterator 与SortedFileIterator
$iteFile = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
$ite = new SortedFileIterator($itefile,$ext);
foreach($ite as $cur){
$pathname=$cur->getPathname();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.