1 回答
TA贡献1884条经验 获得超4个赞
每周间隔的逻辑在我看来是错误的。至少在我的银行应用程序中,每周计划总是在同一个工作日,两次连续发生之间有 7 天。
因此,根据该逻辑,您可以使用此功能:
function getScheduleBetween($data, $intervalStart, $intervalEnd) {
$ref = [
"yearly" => [12, "months"],
"annually" => [12, "months"],
"biannually" => [6, "months"],
"quarterly" => [3, "months"],
"monthly" => [1, "months"],
"weekly" => [7, "days"],
"daily" => [1, "days"]
];
$intervalStart = new DateTime($intervalStart);
$intervalEnd = new DateTime($intervalEnd);
$result = [];
foreach($data as $schedule) {
// Convert start/end to DateTime
$startDate = new DateTime($schedule["startDate"]);
$endDate = $schedule["endDate"] ? min(new DateTime($schedule["endDate"]), $intervalEnd) : $intervalEnd;
$name = $schedule["name"];
$interval = $schedule["intervalType"];
if (!isset($ref[$interval])) throw "Invalid interval type";
list($coeff, $interval) = $ref[$interval];
$match = clone $startDate;
if ($match < $intervalStart) {
$diff = $intervalStart->diff($match);
$count = $interval == "days" ? $diff->format("%a") : $diff->m + $diff->y * 12 + ($diff->d ? 1 : 0);
$count = ceil($count / $coeff) * $coeff;
$match->modify("+$count $interval");
}
while ($match <= $endDate) {
$temp = clone $match;
$result[] = ["name" => $name, "date" => $temp->format("Y-m-d")];
$match->modify("+$coeff $interval");
}
}
array_multisort(array_column($result, "date"), $result);
return $result;
}
使用示例:
$data = [
["name" => "rent", "intervalType" => "monthly", "startDate" => "2019-01-01", "endDate" => "2020-10-11", "amount" => -500],
["name" => "utility", "intervalType" => "monthly", "startDate" => "2019-01-01", "endDate" => "2020-10-11", "amount" => -150],
["name" => "salary", "intervalType" => "monthly", "startDate" => "2019-01-01", "endDate" => "2020-10-11", "amount" => 1700],
["name" => "investment", "intervalType" => "biannually", "startDate" => "2019-02-10", "endDate" => null, "amount" => 2500],
["name" => "food", "intervalType" => "weekly", "startDate" => "2019-01-01", "endDate" => null, "amount" => -50],
];
$result = getScheduleBetween($data, "2019-05-01", "2019-05-31");
print_r($result);
随着更大的时期:
$result = getScheduleBetween($data, "2019-05-01", "2019-08-31");
print_r($result);
如果您有其他类型的间隔,我相信您可以轻松扩展此功能以支持它们,即使使用“每周”的其他逻辑。
- 1 回答
- 0 关注
- 118 浏览
添加回答
举报