
本文讲解如何基于目标时间(如 $prop['created_date'])筛选二维数组中 datetime 字段与之时间差不超过 10 分钟的记录,并构建仅含文件名和时间的二维结果数组。
本文讲解如何基于目标时间(如 `$prop['created_date']`)筛选二维数组中 datetime 字段与之时间差不超过 10 分钟的记录,并构建仅含文件名和时间的二维结果数组。
在处理日志、上传文件列表或时序数据时,常需按时间窗口(如 ±10 分钟)快速过滤匹配项。本例中,$obj['files'] 是一个二维数组,每行代表一个文件,其中 $file[0] 为文件名,$file[6] 为格式为 "Y-m-d H:i:s" 的字符串时间;而 $prop['created_date'] 是一个 IP_DateTime 对象(类似 DateTime),不能直接用于 strtotime()。若忽略类型差异,原始代码会因 strtotime($createDate) 返回 false 导致计算错误。
✅ 正确做法是:先将 IP_DateTime 对象标准化为标准时间字符串,再统一用 strtotime() 转换为时间戳进行比较。以下是完整、健壮的实现:
$createDate = $prop['created_date'];
// 安全提取并格式化目标时间(兼容 IP_DateTime 对象)
if ($createDate instanceof DateTimeInterface) {
$targetTimestamp = $createDate->getTimestamp();
} else {
// 回退:尝试字符串解析(仅当 $createDate 是字符串时)
$targetTimestamp = strtotime((string)$createDate);
}
if ($targetTimestamp === false) {
throw new InvalidArgumentException('Invalid created_date format');
}
$result = [];
foreach ($obj['files'] as $file) {
// 验证必要字段存在且非空
if (!isset($file[0], $file[6]) || !is_string($file[6])) {
continue;
}
$fileName = $file[0];
$fileDateTimeStr = $file[6];
$fileTimestamp = strtotime($fileDateTimeStr);
if ($fileTimestamp === false) {
continue; // 跳过非法时间格式
}
$diffSeconds = abs($fileTimestamp - $targetTimestamp);
if ($diffSeconds <p>? <strong>关键说明与注意事项:</strong> </p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5233" title="btpanel phpsite 宝塔面板PHP网站"><img
src="https://img.php.cn/upload/skill/000/000/081/179040786932301.jpg" alt="btpanel phpsite 宝塔面板PHP网站" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill5233" title="btpanel phpsite 宝塔面板PHP网站" class="overflowclass">btpanel phpsite 宝塔面板PHP网站</a>
<p class="overflowclass">宝塔面板 PHP 网站管理:站点创建、删除、启停、PHP 版本切换、域名管理、SSL证书管理、伪静态管理、数据库管理</p>
</div>
<a rel="nofollow" href="/xiazai/skill5233" title="btpanel phpsite 宝塔面板PHP网站" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
- ✅ 避免
array_push($result, $file):原代码意图是存[name, datetime],但array_push($result, $file)会把整个 9 元素数组压入,导致结构错误;应显式构造子数组[$fileName, $fileDateTimeStr]。 - ✅
$result[] = ...更简洁安全:相比手动维护$index,PHP 数组的自动索引赋值更符合习惯且不易出错。 - ⚠️ 时间对象兼容性:
IP_DateTime是自定义类(常见于某些 SDK),务必通过getTimestamp()或format('Y-m-d H:i:s')转为可解析格式,不可直接传给strtotime()。 - ? 容错增强:添加了
isset检查与strtotime()返回值校验,防止因脏数据导致脚本中断或逻辑偏差。 - ? 时区一致性:确保
$createDate和$file[6]所在时区一致(如均为America/Sao_Paulo)。若$file[6]无时区信息,默认按服务器本地时区解析;如有需要,可用DateTime::createFromFormat()显式指定时区。
最终输出为标准 JSON 格式的二维数组,例如:
[ ["20220407_10_22_30_L100.SVL", "2022-04-07 13:34:10"], ["20220425_03_38_22_L101.SVL", "2022-04-25 03:38:15"] ]
该结构清晰、轻量,可直接用于前端渲染或后续 API 交互。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










