user6263663
user6263663

Reputation:

Multiply price and quantity of each row, then sum to calculate total

My code goes as:

<?php        
$items = array(
    array("SKU" => "a49w8dsa", "Title" => "Socks", "Description" => "Sports socks", "Price" => "1.50", "Quantity" => "4"),
    array("SKU" => "ta8dla", "Title" => "T-shirt", "Description" => "ABC Brand undershirt", "Price" => "14.25", "Quantity" => "2"),
    array("SKU" => "yusa982", "Title" => "Flip Flips", "Description" => "XYZ Brand Beach Flops", "Price" => "2.88", "Quantity" => "5"),
    array("SKU" => "gnbaiue", "Title" => "Ball Cap", "Description" => "No Name", "Price" => "3.58", "Quantity" => "1"),
    array("SKU" => "ythwq836", "Title" => "Frizbee", "Description" => "Whammo Frisbee Disc", "Price" => "2.47", "Quantity" => "2")
);

$final = array_shift($items);
foreach (array_column as $key => &$value){
    $value += array_sum(array_row($Price . $Quantity));
}
unset($value);
var_dump($final);

I want to grab the price of each item, multiply it by the quantity in that array and add the sums to a variable, then print.

Upvotes: 1

Views: 926

Answers (1)

jitendrapurohit
jitendrapurohit

Reputation: 9675

Get price of each item into an array, then finally sum it up using array_sum() -

$eachPrice = array();
foreach ($items as $key => $val) {
  $eachPrice[] = $val['Price'] * $val['Quantity'];
}

$totalPrice = array_sum($eachPrice);

var_dump($totalPrice); // should be total price of all items

Upvotes: 1

Related Questions