php - 我如何为每日费用制作一个每月分配值的日期计算器
问题描述
我想做一个php计算器。首先,我希望它每个月的每天都有一个分配的值。例如,三月每日价值为 12 美元,一月为 7 美元。基于这些值,我希望计算器从选定的日期日历计算每日费用。然后是总成本。任何想法我该怎么做?有什么文章可以帮助我吗?先感谢您!!!
解决方案
这可能会对您有所帮助。首先设置期间的开始和结束日期。然后,该逻辑将每个月的“天数”存储在 中,$dates[]
并将每个月的天数相加,存储在$daysPerMonth[]
. 最后,使用$charges[]
数组,在每个月的天数中循环并乘以设定的费用。
数组totalCharges[]
显示每月的总数。总计,该期间的总和。
<?php
$start = "2021-01-01";
$end = "2022-01-10";
$start = new DateTime($start);
$end = new DateTime($end);
$interval = new DateInterval('P1D');
$end = $end->modify( '+1 day' ); // include end date
$period = new DatePeriod($start, $interval, $end);
// store dates
$dates = [];
$format = 'm'; // only month is of interest
foreach ($period as $date) {
$dates[] = $date->format($format);
}
$daysPerMonth = array_count_values($dates); // count days per month
// set charges per month
$charges = ['01' => 7, '02' => 9, '03' => 12, '04' => 13, '05' => 14, '06' => 15,
'07' => 16, '08' => 15, '09' => 12, '10' => 9, '11' => 8, '12' => 7];
$totalCharges = []; // store total charges per month
foreach($charges as $monthly => $charge) {
foreach($daysPerMonth as $month => $days) {
if($monthly == $month) $totalCharges[$month] = $charge * $days;
}
}
print_r($totalCharges); // total charges per month
echo 'Grand Total : ' . array_sum($totalCharges);
推荐阅读
- javascript - 如何使用电子中的按钮打开 exe 文件
- python - pandas wide_to_long IndexError 是什么意思?
- enums - Rust - 将特征包装在枚举中以进行内存布局和更简单的泛型?
- r - 修改正则表达式匹配的子串并放回
- sql - 无法弄清楚如何从这种情况下创建一个 select 语句?
- qt - QML:打开窗口后如何显示对话框?
- variables - 从 Ansible 控制服务器获取时间戳并将其添加到远程系统上运行的命令中
- linux - 将 blazor 服务器端 .net 核心应用程序从 linux 容器(docker)内部连接到内部网络 Active Directory 的最佳方法?
- python - Python中的e-0是什么意思?
- docker - 如何通过命令行指定在 docker-compose 中使用哪个 env_file