Reputation: 3573
I hope this makes sense. Right now I am using the following code to add up number of checkboxes check and get a shipping price based off that number. This only gets me one set off shipping prices (ground). I know want to add mulitpble shipping options so I need to add another set of switch/case statement.
//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 ;
}
}
If $shippingChoice = $_POST['ShipMethod'];
is getting my ship method, how can I use that to select what switch/case statement to use. Like if $shippingChoice
returned the value of "ground" it would use my current switch/case statement.If it returned "2 Day" it would use another switch/case statement I would make.
Upvotes: 0
Views: 110
Reputation: 10033
You want something like this? Add a subarray for other shipping methods.
$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']);
You can also use something like this to filter shipping methods to make sure it is valid.
$method = (isset($shippingCostData[$_POST['shippingMethod']]) ? $_POST['shippingMethod'] : key($shippingCostData));
Upvotes: 1
Reputation: 437396
You should define the shipping charges in another form that is more malleable at run time. For example:
$costs = [
1 => 14.99, // 1 or more = 14.99
6 => 15.99, // 6 or more
7 => 16.99,
9 => 17.99,
];
You can then write a function that takes the number and the costs array and returns the cost:
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;
}
After you have done this, it's easy to keep multiple costs arrays and forward to the one you need, e.g.
$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]);
You can easily extend this to as many shipping methods as you like.
Upvotes: 1