假设我们有1300个单元。现在我想第一个500单位的价格是12欧元,另一个800单位的价格9欧元。
所以我基本需要的是一个函数,它计算一个总数,得到第一个500*12欧元,另一个800*9欧元。但总的单位也可以是5000,而不是这个例子中的1300单位,它的用户输入的密码。
<?php
$total = 1300;
$sub = 1;
$sub2 = 1;
for($i=1; $i<=$total; $i++)
{
for($sub; $i<=500; $sub++)
{
$sub2 += $sub;
break;
}
}
echo $sub2;
?>
<?php
$units = 1300;
$cut_off=500;//made it a var just in case
$a=12;//fist 500
$b=9;//rest
//verbose calculations, you don't really need to create the extra variables
$a_total=$cut_off*$a;
$b_total=($units-$cut_off)*$b;
$grand_total=$a_total+$b_total;
?>
如果估算的单位小于500,您可能应该添加一个复选框。否则事情会变成奇怪的
更新:
<?php
function calc_total($qtt, $min = 500, $fst_price = 12, $nxt_price = 9){
if($qtt > $min) return false; // Check if the minimum 500 was sent.
/* First calculate the rest, which is the quantity sent by
the user without the minimum x 9. Then add the minimum x 12 */
$total = (($qtt - $min) * 9) + ($min * 12);
return $total;
}
?>
你可以这样调用函数:
echo "$". calc_total(1300);