首页 > 解决方案 > 我如何为每日费用制作一个每月分配值的日期计算器

问题描述

我想做一个php计算器。首先,我希望它每个月的每天都有一个分配的值。例如,三月每日价值为 12 美元,一月为 7 美元。基于这些值,我希望计算器从选定的日期日历计算每日费用。然后是总成本。任何想法我该怎么做?有什么文章可以帮助我吗?先感谢您!!!

标签: php

解决方案


这可能会对您有所帮助。首先设置期间的开始和结束日期。然后,该逻辑将每个月的“天数”存储在 中,$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);

推荐阅读