Php if语句选择switch语句
我希望这是有道理的。现在,我正在使用以下代码将复选框的数量相加,并根据该数字获得装运价格。这只让我得到一个抵消航运价格(地面)。我知道我想添加多个装运选项,所以我需要添加另一组switch/case语句Php if语句选择switch语句,php,if-statement,switch-statement,Php,If Statement,Switch Statement,我希望这是有道理的。现在,我正在使用以下代码将复选框的数量相加,并根据该数字获得装运价格。这只让我得到一个抵消航运价格(地面)。我知道我想添加多个装运选项,所以我需要添加另一组switch/case语句 //Add up club totals for shipping $clubTotal = array( $driversChecked, $hybridsC
//Add up club totals for shipping
$clubTotal = array(
$driversChecked,
$hybridsChecked,
$woodsChecked,
$boxesChecked,
$wedgesChecked,
);
//see what shipping was picked
$shippingChoice = $_POST['ShipMethod'];
//Figure out ground shipping
if (array_sum($clubTotal))
{
switch(array_sum($clubTotal))
{
case 6:
$shippingCost = 15.99 ;
break ;
case 7:
case 8:
$shippingCost = 16.99 ;
break ;
case 9:
case 10:
$shippingCost = 17.99 ;
break ;
case 11:
case 12:
$shippingCost = 18.99 ;
break ;
case 13:
$shippingCost = 19.99 ;
break ;
case 14:
$shippingCost = 20.99 ;
break ;
case 15:
$shippingCost = 21.99 ;
break ;
case 16:
$shippingCost = 22.99;
break ;
default:
$shippingCost = 14.99;
break ;
}
}
如果
$shippingChoice=$\u POST['shippmethod']
正在获取我的ship方法,如何使用它来选择要使用的switch/case语句。例如,如果$shippingChoice
返回“ground”的值,它将使用我当前的switch/case语句。如果它返回“2天”,它将使用我将使用的另一个switch/case语句。您想要这样的东西吗?为其他装运方法添加子阵列
$shippingCostData = array(
'ground' => array(
6 => 15.99,
7 => 16.99,
8 => 16.99,
9 => 17.99,
10 => 17.99,
11 => 18.99,
12 => 18.99,
13 => 19.99,
14 => 20.99,
15 => 21.99,
16 => 22.99,
'default' => 14.99,
),
);
$method = 'ground';
$clubTotalSum = array_sum($clubTotal);
$shippingCost = (isset($shippingCostData[$method][$clubTotalSum]) ? $shippingCostData[$method][$clubTotalSum] : $shippingCostData[$method]['default']);
您还可以使用类似的方法来筛选装运方法,以确保其有效
$method = (isset($shippingCostData[$_POST['shippingMethod']]) ? $_POST['shippingMethod'] : key($shippingCostData));
您应该以另一种在运行时更具可塑性的形式定义运费。例如:
$costs = [
1 => 14.99, // 1 or more = 14.99
6 => 15.99, // 6 or more
7 => 16.99,
9 => 17.99,
];
然后,您可以编写一个函数,该函数接受数字和成本数组并返回成本:
function calculateCost($items, $costs) {
ksort($costs); // just to be on the safe side
$result = reset($costs);
foreach($costs as $number => $cost) {
if ($number > $items) break;
$result = $cost;
}
return $result;
}
完成此操作后,很容易保留多个成本阵列并转发到所需的阵列,例如
$costs = [
'ground' => [
1 => 14.99,
6 => 15.99,
],
'air' => [
1 => 24.99,
6 => 25.99,
],
];
$shippingChoice = $_POST['ShipMethod'];
$cost = calculateCost(array_sum($clubTotal), $costs[$shippingChoice]);
您可以轻松地将其扩展到任意多个装运方式。我看不出这个switch语句有什么意义。为什么这些运输成本值不存在于stdClass中,您可以根据数组键(基于您的结构)引用该值,该值类似于1-16?我不喜欢这种方法,因为您必须确保填充的成本数组达到最大可能的总和,否则代码会工作,但会做错误的事情(返回“默认”值)。@Jon但它很容易理解,使用也很简单。KISS.KISS不是邀请臭虫的借口,特别是在涉及金钱的时候。这将是很容易适应,这样就没有机会出现这样的问题,我想你应该。我试过的代码,它似乎打破了。我想我唯一不懂的部分是
函数。我是否应该将$items
定义为等于选中的复选框数???@Packy:基本上等于数组的总和($clubTotal)
是多少。“Items”是我对它的解释。这就是我的想法,我将$Items定义为它,但它仍然不稳定。现在我有$cost
数组、$shippingChoice
、$cost
和函数。这是正确的顺序吗?我不确定函数的$number
部分。