php - 返回某个日期范围内的目录中的文件
问题描述
我有一个目录,里面有一堆文件。我可以使用 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 之前),以便我可以根据需要拥有“下一个”和“上一个”页面。
有可能做我要求的吗?
解决方案
我不认为有一个内置函数可以神奇地过滤日期。你可以自己卷起来。
这是一个想法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;
}
}
所以基本上接受 aFROM
和TO
参数,就像你通常在查询中所做的那样。
只需将块内的逻辑更改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
如果您选择这样做,您可以使用类。
推荐阅读
- bash - Bash:点命令双重麻烦
- amazon-web-services - 从 AWS Firehouse 到 S3 的数据安全性
- npm-install - lerna add : 在哪里找不到包
可以添加 - c++ - C++插件架构设计
- react-native - 如何使用 expo 托管工作流创建离线 apk(不使用 expo 发布或托管资产)?
- android - 如何使用 Hilt 提供测试改造 url
- c - 我找不到这个 C 程序有什么问题来使用函数检查一个数字是否是素数
- c# - 在 C# 中以编程方式使用 Openstack API
- reactjs - 合并 useQuery 和 useLazyQuery 的结果 - React Apollo
- docker - 为什么错误 FileNotFoundError: [Errno 2] No such file or directory: './ML/model.pth' 发生?