【问题标题】:Return files in a directory between a certain date range返回某个日期范围内的目录中的文件
【发布时间】:2019-12-06 08:42:27
【问题描述】:

我有一个目录,里面有一堆文件。我可以使用 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 之前),以便我可以根据需要拥有“下一个”和“上一个”页面。

是否可以按照我的要求去做?

【问题讨论】:

    标签: php date filter directory iterator


    【解决方案1】:

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

    这是一个来自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;
        }
    }
    

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

    只需将 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 类。

    【讨论】:

    • 我从来没有遇到过FilterIterator 类。这非常方便!正是我想要的。
    猜你喜欢
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2014-01-07
    • 1970-01-01
    相关资源
    最近更新 更多