使用php计算基于产品重量的运费

时间:2015-03-10 01:35:51

标签: php

我必须计算具有重量的产品的运费。我的体重是克,即1000克是1公斤。

交货价格为2.80美元,最高3公斤,然后每增加一公斤0.76美元。

最大重量为100公斤。我可以做 - 如果 - 或者切换,但我想提出一些更优雅的解决方案。任何帮助都将深表感谢。

问候,约翰

3 个答案:

答案 0 :(得分:2)

$cost = $kg <= 100 ? max(array($kg - 3 , 0)) * 0.76 + 2.80 : false

如果$kg小于100,则:

减去3公斤,

如果结果是否定的,则将其设置为0.将剩余的kg每公斤乘以0.76美元。

最后,为最初的第一个“最多3”kg添加2.80美元的基本成本。

如果基本重量超过100,则返回false,因为它超出范围。

以克:

$cost = $g <= 100*1000 ? max(array($g - 3*1000 , 0)) * 0.76/1000 + 2.80 : false

答案 1 :(得分:2)

如果你想要一些可读的东西(并猜测你不想圆):

if($weight <3000){
$shipping=2.8;
}elseif ($weight <100000){
$shipping=2.8+(0.00076*($weight-3000));
}else{
$shipping="to heavy";
}

echo $shipping //format $shipping depending on currency

答案 2 :(得分:-2)

尝试像

这样的无限循环
$weight = $weightStart
$costs = 0;
 while ($weight > 0)
 {
 if ($weight < 3){$costs += 2.80;$weightOnce=3} else {$costs = 0.76;$weightOnce = 1;}
 $weight -= $weightOnce;
 }

echo $costs;
相关问题