PHP酒店入住日期拆分异常问题排查与修复求助
酒店入住日期拆分异常排查请求
我开发了一套基于配额数据合并/拆分酒店入住日期并生成Excel的系统,其余功能正常,但部分起始日期无法正确拆分合并。已尝试多种方案无果,附上相关信息求协助:
相关资料
1. 核心拆分逻辑PHP代码片段
// 日期拆分合并核心函数 function splitMergeDates($start, $end, $quotaList) { $segments = []; $currentStart = $start; $currentQuota = getQuotaByDate($currentStart, $quotaList); while (strtotime($currentStart) <= strtotime($end)) { $nextDay = date('Y-m-d', strtotime($currentStart . ' +1 day')); $nextQuota = getQuotaByDate($nextDay, $quotaList); // 若下一日配额不同或已到结束日期,生成当前段 if ($nextQuota != $currentQuota || strtotime($nextDay) > strtotime($end)) { $segments[] = [ 'start_date' => $currentStart, 'end_date' => $currentStart, 'quota' => $currentQuota ]; $currentStart = $nextDay; $currentQuota = $nextQuota; } else { // 合并连续同配额日期 $currentStart = $nextDay; } } return $segments; } // 根据日期获取配额 function getQuotaByDate($date, $quotaList) { foreach ($quotaList as $item) { if ($item['date'] == $date) { return $item['quota']; } } return 0; }
2. 数据库示例数据
| 日期 | 配额 |
|---|---|
| 2024-05-01 | 2 |
| 2024-05-02 | 2 |
| 2024-05-03 | 1 |
| 2024-05-04 | 1 |
| 2024-05-05 | 3 |
3. 当前错误输出
| 起始日期 | 结束日期 | 配额 |
|---|---|---|
| 2024-05-01 | 2024-05-02 | 2 |
| 2024-05-03 | 2024-05-03 | 1 |
| 2024-05-04 | 2024-05-04 | 1 |
| 2024-05-05 | 2024-05-05 | 3 |
4. 期望正确输出
| 起始日期 | 结束日期 | 配额 |
|---|---|---|
| 2024-05-01 | 2024-05-02 | 2 |
| 2024-05-03 | 2024-05-04 | 1 |
| 2024-05-05 | 2024-05-05 | 3 |
排查方向建议
- 数据类型匹配问题:检查
getQuotaByDate返回值的类型,数据库中的配额如果是字符串类型(如'1'),和整数1用!=比较会导致判断错误,可强制转换为整数:return (int)$item['quota']; - 日期转换边界错误:用
DateTime类替代strtotime避免时区偏差,比如:$currentStartDt = new DateTime($currentStart); $nextDayDt = (clone $currentStartDt)->modify('+1 day'); $endDt = new DateTime($end); - 循环逻辑漏洞:当前合并逻辑未正确记录结束日期,修正后的逻辑应保留起始日期,直到配额变化时再设置结束日期:
$segments = []; $currentStart = $start; $currentQuota = getQuotaByDate($currentStart, $quotaList); $currentEnd = $start; while (strtotime($currentEnd) <= strtotime($end)) { $nextDay = date('Y-m-d', strtotime($currentEnd . ' +1 day')); $nextQuota = getQuotaByDate($nextDay, $quotaList); if ($nextQuota == $currentQuota && strtotime($nextDay) <= strtotime($end)) { $currentEnd = $nextDay; } else { $segments[] = [ 'start_date' => $currentStart, 'end_date' => $currentEnd, 'quota' => $currentQuota ]; $currentStart = $nextDay; $currentEnd = $nextDay; $currentQuota = $nextQuota; } } - 配额数据排序问题:确保
$quotaList按日期升序排列,避免getQuotaByDate匹配错误,可添加排序逻辑:usort($quotaList, function($a, $b) { return strcmp($a['date'], $b['date']); });
内容的提问来源于stack exchange,提问作者Laquire
相关产品推荐
相关产品推荐

