我正在建立一个联邦快递的运费计算器,当我需要运送一件物品时工作正常,但有时我需要运送多件物品。 代码:
$xyz=calcShip(30,4,4,2.5);
foreach ($xyz as $sType => $tCost){
print $sType ." ". $tCost . "<br>";
}
印刷品看起来像这样:
Priority Overnight 32.49
Standard Overnight 60.38
2 Day 28.58
Express Saver 22.08
Ground 8.35
但是如果我想一个接一个地计算多个货物并且货物类型总是以相同的顺序排列5个,那么我如何才能为每种类型添加所有价格?
答案 0 :(得分:1)
$ship_cost = array();
function addShipping($arr){
foreach ($arr as $sType => $tCost){
$ship_cost[$sType] += $tCost;
}
}
function showTotalShipping(){
foreach($ship_cost as $sType => $tCost){
print $sType ." ". $tCost . "<br>";
}
}
addShipping(calcShip(12,6,6,5.5));
addShipping(calcShip(30,4,4,2.5));
showTotalShipping();
答案 1 :(得分:0)
$total = array();
$shipping_parameters = array(
// each shipping calculation would be added as an array here eg.
array(30,4,4,2.5),
array(29,3,3,3),
);
foreach($shipping_parameters as $shipping_param) {
$xyz = call_user_func_array('calcShip', $shipping_param);
foreach ($xyz as $sType => $tCost){
if(!isset($total[$sType])) {
$total[$sType] = 0;
}
$total[$sType] += $tCost;
}
}
print_r($total);