以 php 为单位增加价格,以公里为单位



我正在尝试根据提供给它的公里数提高价格。

信息:1公里=1000米

我想要实现的目标

if ($km <= 3000) {
//if provided KM is less than and equal to 3 km
//output $3.99(base price) 
}elseif ($km > 3000) {

//if provided km is greater then 3km and on every +1 km, will increase $0.50c in $3.99

//example: if km is 3400 then $3.99(base price) + $0.50c
//example: if km is 4000 then $3.99 + $0.50c
//example: if km is 5000 then $3.99 + $0.50c + $0.50c
//so on..
}

但我觉得我的方法太糟糕了...如果不是if conditions而是有一个algo使用loop执行此任务会更好。

你只需要计算3000后的公里数。因此,对于第二种情况,价格将是:

$output = $base_price + (intval($km - 3000) / 1000) * 0.5;

我认为这就是你想要的;

$base_price=4;
$increase_price=0;
$km=5200;
if($km > 3000){
$difference_km = ($km-3000)/1000;
$difference_floor = floor($difference_km);
$increase_price = $difference_floor*0.5;
}
$output = $base_price + $increase_price;
echo $output;
// output will be 5
<?php
$price = 3.99;
$kms = [3400, 4000, 5000, 6000];
foreach ($kms as $km) {
$profit=0;
if ($km > 3000) {
$profit = intval(($km-3000)/1000);
}
echo("{$km}km = $$price".str_repeat(' + $0.50c',$profit)."<br>");
}
/*Output:
3400km = $3.99
4000km = $3.99 + $0.50c
5000km = $3.99 + $0.50c + $0.50c
6000km = $3.99 + $0.50c + $0.50c + $0.50c
*/
die();
?>

最新更新