Home > database >  How do you add Together PRICE from multiple Arrays Columns?
How do you add Together PRICE from multiple Arrays Columns?

Time:12-04

I am trying to build my own "Shopping Cart" system and I want to take all of the ['Price'] columns and add them together to get a total for the sale. I am trying to push them out into a $variable or $_SESSION['total']; so I can display it to the end user.

array(3) {
    [1]=>
    array(4) {
      ["Qty"]=>
      string(1) "1"
      ["Price"]=>
      string(1) "1"
      ["Name"]=>
      string(4) "Coke"
    }
    [2]=>
    array(4) {
      ["Qty"]=>
      string(1) "1"
      ["Price"]=>
      string(1) "1"
      ["Name"]=>
      string(4) "Coke"
    }
    [3]=>
    array(4) {
      ["Qty"]=>
      string(1) "1"
      ["Price"]=>
      string(1) "1"
      ["Name"]=>
      string(4) "Coke"
    }
  }

CodePudding user response:

Assuming you already have the same array you mentioned above:

$total = array_column( $array, 'Price' ); // taking the array and getting the values of the price
$total = array_sum( $total ); // add the values together to get the total price from it
// now you can put it in session too if you want
$_SESSION['CART_TOTAL_PRICE'] = $total;

CodePudding user response:

You'll need to loop over each product in the cart array and add the price total to a variable. Something like this:

$price_total = 0;

// If you need to take quantity into account
foreach ($order_product as $product) {
  $price_total = $price_total   ($product['Qty'] * $product['Price']);
}

// If you don't need to take quantity into account
foreach ($order_product as $product) {
  $price_total = $price_total   $product['Price'];
}
  • Related