首页 > 解决方案 > 返回某个日期范围内的目录中的文件

问题描述

我有一个目录,里面有一堆文件。我可以使用 DirectoryIterator 获取所有文件。

$files = new DirectoryIterator('/path/to/directory/');

除此之外,我还可以使用 RegexIterator 和 LimitIterator 过滤返回的文件。

$regex_iterator = new RegexIterator($files, '/my_regex_here/');
$limit_iterator = new LimitIterator($regex_iterator, $offset, $limit);

这很好用,因为它只返回我需要的文件。有没有一种方法可以只返回在特定日期范围内创建的文件,类似于使用 RegexIterator(通过匹配文件名上的正则表达式进行过滤)?类似于 SQL 查询:

SELECT * FROM table WHERE created_date BETWEEN 'first_date' AND 'second_date';

我可以循环 $limit_iterator 中的所有文件并检查文件的创建时间,但我想避免从迭代器类返回不必要的文件,因为目录中可能有很多文件。

为了分页,我还需要基于这些过滤器的文件总数(在使用 LimitIterator 之前),以便我可以根据需要拥有“下一个”和“上一个”页面。

有可能做我要求的吗?

标签: phpdatefilterdirectoryiterator

解决方案


我不认为有一个内置函数可以神奇地过滤日期。你可以自己卷起来。

这是一个想法FilterIterator

class FileDateFilter extends FilterIterator
{
    protected $from_unix;
    protected $to_unix;

    public function __construct($iterator, $from_unix, $to_unix)
    {
        parent::__construct($iterator);
        $this->from_unix = $from_unix;
        $this->to_unix = $to_unix;
    }

    public function accept()
    {
        return $this->getMTime() >= $this->from_unix && $this->getMTime() <= $this->to_unix;
    }
}

所以基本上接受 aFROMTO参数,就像你通常在查询中所做的那样。

只需将块内的逻辑更改accept为您的业务需求即可。

因此,当您实例化自定义过滤器时:

$di = new DirectoryIterator('./'); // your directory iterator object
// then use your custom filter class and feed the arguments
$files = new FileDateFilter($di, strtotime('2017-01-01'), strtotime('2018-01-01'));
$total = iterator_count($files);
foreach ($files as $file) {
    // now echo `->getFilename()` or `->getMTime()` or whatever you need to do here
}
// or do the other filtering like regex that you have and whatnot

旁注:DateTime如果您选择这样做,您可以使用类。


推荐阅读