代码必须在PHP,这是怎么可能的?
我想根据以下原则计算价格:
0-50 = 3pr单位
50-100 = 2.5 pr单位
100-150 = 2pr单位
150+ = 1.5 pr单位
例如,125件的订单成本为:
(50 * 3) + (50 * 2,5) + (25 * 2) = 325
我认为这可以用while循环来完成,或者可能有一些函数可以更容易地完成?
function calculatePrice($numberOfUnits) {
// Initialise price
$price = 0;
// Prices: amount for category => price for category
// Starts with largest category
$prices = array(150 => 1.5, 100 => 2, 50 => 2.5, 0 => 3);
// Loop over price categories
foreach($prices as $categoryAmount => $categoryPrice) {
// Calculate the numbers that fall into the category
$amount = $numberOfUnits - $categoryAmount;
// If units fall into the category, add to the price
// and calculate remaining units
if($amount > 0) {
$price += $amount*$categoryPrice;
$numberOfUnits -= $amount;
}
}
// Return the total price
return $price;
}
你可以在这里看到它的作用
方法1:你可以创建一个循环,检查number是否小于或大于一个值(50,100…)来设置单价
$value = 1000;
echo getPrice($value);
function getPrice($value)
{
$price = 0;
$prices = array(3,2.5,2,1.5);
for ( $i = 1 ; $i <= $value ; $i++ )
{
if ( $i < 50 ) $price += $prices[0];
else if ( $i < 100 ) $price += $prices[1];
else if ( $i < 150 ) $price += $prices[2];
else $price += $prices[3];
}
return $price;
}
方法二:可以计算每个价格区间
$value = 1000;
echo getPrice($value);
function getPrice($value)
{
$price = 0;
$prices = array(3,2.5,2,1.5);
if ( $value > 150 )
return $prices[0] * 50 + $prices[1] * 50 + $prices[2] * 50 + ( $value - 150 ) * $prices[3];
if ( $value > 100 )
return $prices[0] * 50 + $prices[1] * 50 + ( $value - 100 ) * $prices[2];
if ( $value > 50 )
return $prices[0] * 50 + ( $value - 50 ) * $prices[1];
return $value * $prices[0];
}