是否有一种快速的方法来根据天数来减少租金?
例如:
If I rent a car for 1day, the cost is 100$
If I rent a car for 2days, the cost is 100$ + 70$ = 170$
If I rent a car for 3days, the cost is 100$ + 70$ + 50$ = 220$
If I rent a car for 4days, the cost is 100$ + 70$ + 50$ + 50$ = 270$
If I rent a car for 5days, the cost is 100$ + 70$ + 50$ + 50$ + 50$ = 320$
因此,我需要一种快速的方法来根据天数获取总费用。 例如:
function getcost(days){
...
return $cost;
}
echo getcost(1); // it show 100$
echo getcost(3); // it show 220$
// and so on...
答案 0 :(得分:1)
假设从第三天开始,所有连续天的费用为50美元:
function getcost(int $days) {
return ($days > 1) ? (($days - 2) * 50 + 170) : (($days == 1) ? 100 : 0);
}
答案 1 :(得分:0)
function getcost(days){
$cost=0;
for($idx=1;$idx<=$days;$idx++)
{
switch($idx)
{
case 1:
$cost+=100;
break;
case 2:
$cost+=70;
break;
default:
$cost+=50;
break;
}
}
return $cost;
}
答案 2 :(得分:0)
$price = $days * 50 + ($days > 1 ? 70 : 20);
如果需要,可以将其放入函数中。
答案 3 :(得分:0)
您可以尝试这样-
<?php
function getcost($days){
$array=['base' => 100, 'for_2nd' => 70, 'after_2nd' => 50];
if($days==1){
$cost = $array['base'] * $days;
}else if($days>=2){
$cost = $array['base'] + ($days == 2 ? $array['for_2nd'] : $array['for_2nd'] + ($days - 2) * $array['after_2nd']);
}
return $cost.'$';
}
echo getcost(1); // it show 100$
echo getcost(2); // it show 170$
echo getcost(3); // it show 220$
echo getcost(4); // it show 270$
echo getcost(5); // it show 320$
?>
答案 4 :(得分:0)
如果您的日费率是基于天数的,那么为了让您拥有动态费率(也许是不同类型的汽车等),那么最好将某种形式的数组传递给函数。然后,该函数会使用它并添加直到价格用完的天数,然后根据最后的价格添加剩余的天数...
// Cost for each day
$costs = [100, 70, 50];
function getcost( $costs, $days){
$totalCost = 0;
foreach ( $costs as $dayCost ) {
// Add each cost
$totalCost += $dayCost;
// Decrement number of days left and exit if reached 0
if ( --$days == 0 ) {
break;
}
}
// If remaining days - add last day cost * number of days
if ($days > 0 ) {
$totalCost += ($dayCost*$days);
}
return $totalCost;
}
echo getcost($costs, 1); // it show 100$
echo getcost($costs, 3); // it show 220$
echo getcost($costs, 5); // it show 320$