开发者

How to add numbers in multiple arrays

开发者 https://www.devze.com 2023-03-24 12:15 出处:网络
Im building a shipping calculator for fedex which is working fine when i need to ship one item, but sometimes i need to ship 开发者_运维技巧multiple items.

Im building a shipping calculator for fedex which is working fine when i need to ship one item, but sometimes i need to ship 开发者_运维技巧multiple items. code:

$xyz=calcShip(30,4,4,2.5);
foreach ($xyz as $sType => $tCost){
    print $sType ." ". $tCost . "<br>";
}

the print looks like this:

Priority Overnight 32.49
Standard Overnight 60.38
2 Day 28.58
Express Saver 22.08
Ground 8.35

but if i want to calculate multiple shipments one after another and the shipment types are always those 5 in the same order, how can i just add all of the prices together for each type?


$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();


$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);
0

精彩评论

暂无评论...
验证码 换一张
取 消