我需要根据范围计算商品的总成本:
if ($itemCount <11)
{
$cost_for_range = 1;
}
if ($itemCount <26 && $itemCount >=11)
{
$cost_for_range = 0.75;
}
if ($itemCount <50 && $itemCount >=26)
{
$cost_for_range = 0.55;
}
事情是 - 我需要考虑到早期水平来计算最终成本 - 例如,如果购物车有 30 件商品,价格将是:
答案 0 :(得分:2)
试试这个:
$itemCount = 25;
$total = 0;
for ( $i = 0 ; $i < $itemCount ; $i++ ) {
if ( $i < 10 ) {
$total += 1;
} else if ( $i < 25 ) {
$total += 0.75;
} else if ( $i < 50 ) {
$total += 0.55;
} else {
$total += 0; // price if more than 50
}
}
答案 1 :(得分:2)
使用 min
和 max
进行各种范围的测试很有趣...
function calculateCost ( int $count, float $cost ) {
$total = min(10, $count) * $cost;
$total += (min(15, max(0, $count - 10)) * ($cost * 0.75));
$total += (max(0, $count - 25) * ($cost * 0.55));
return $total;
}
第二个计算使用 max(0, $count - 10)
,因此这会减去前 10 个,但确保它不会变为负数。然后它使用 min(15, max(0, $count - 10))
取最小的 15 或剩下的数字(因此如果是 30,这将是 15)。
最后一个只是计数的 max
- 25 或 0,因此对于 30,这是 5。
与...一起使用
echo calculateCOst( 30, 1 );
给出 24
答案 2 :(得分:1)
对于通用解决方案,最好在数组中定义折扣。然后,此解决方案可用于扩展和更改。
$rebate = [10 => 1.0, 15 => 0.75, PHP_INT_MAX => 0.55];
数字和折扣数组被转移到计算成本因子的函数中。计算本身是通过带有终止条件的简单 forech 循环实现的。
function calcCostFactor(int $count, array $rebate){
$factor = 0.0;
foreach($rebate as $number => $val){
$factor += min($count,$number) * $val;
$count -= $number;
if($count <= 0) break;
}
return $factor;
}
示例:
$factor = calcCostFactor(30, $rebate);