Есть ли быстрый способ получить уменьшенную стоимость аренды в зависимости от количества дней?
Например:
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...
Предполагая, что с третьего дня все последующие дни стоят 50 $:
function getcost(int $days) {
return ($days > 1) ? (($days - 2) * 50 + 170) : (($days == 1) ? 100 : 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;
}
$price = $days * 50 + ($days > 1 ? 70 : 20);
Если вы хотите, вы можете поместить его в функцию.
Вы можете попробовать так
<?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$
?>
DEMO: https://3v4l.org/h9tF5
Если ваша дневная ставка основана на количестве дней, то для того, чтобы у вас была динамическая скорость (возможно, другой тип автомобиля и т. Д.), Тогда лучше иметь некоторую форму массива, которая передается в функцию. Затем функция использует это и добавляет дни до тех пор, пока не закончатся ставки, и добавляет оставшиеся дни в соответствии с последней ставкой …
// 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$