Jesse Jesse - 1 month ago 6
HTML Question

Add up prices for total price with array values PHP

I'm making a Shopping Cart, actually it's almost finished now. I only want to calculate the total price. The problem is, the prices per product are calculated (price*quantity) in an foreach loop, so I'm not sure how to add up all the prices.

The PHP Function:

public function getCart(){
$cartArray = array();
if(!empty($_SESSION["cart"])){
if($_SESSION['cart'] != ""){
$cart = json_decode($_SESSION['cart'], true);
for($i=0;$i<count($cart);$i++){
$lines = $this->getProductData($cart[$i]["product"]);
$line = new stdClass;
$line->id = $cart[$i]["product"];
$line->count = $cart[$i]["count"];
$line->product = $lines->product;
$line->total = ($lines->price*$cart[$i]["count"]);
$cartArray[] = $line;
}
}
}
return $cartArray;
}


How I display it all:

<?php
$cart = new cart();
$products = $cart->getCart();

$cartCount = 0;
if(isset($_SESSION['cart'])){
$cart = json_decode($_SESSION['cart'], true);
$cartCount = count($cart);
}
if($cartCount > 0){
?>
<table class="table table-striped table-hover">
<tr>
<td align="left"><b>Product</b></td>
<td align="center"><b>Quantity</b></td>
<td align="center"><b>Total</b></td>
<td align="right"></td>
</tr>
<?php
foreach($products as $product){
?>
<tr>
<td align="left"><?php print $product->product; ?></td>

<td align="center">
<?php print $product->count; ?>
&nbsp;&nbsp;
<i style="cursor:pointer;" class="fa fa-minus lessQuantity"
data-id="<?php print $product->id; ?>"></i>
<i style="cursor:pointer;" class="fa fa-plus addQuantity"
data-id="<?php print $product->id; ?>"></i>
</td>

<td align="center">$<?php print $product->total; ?></td>

<td align="right">
<span style="cursor:pointer;" data-toggle="tooltip" title="Delete item."
class="removeFromCart" data-id="<?php print $product->id; ?>"><i class="fa fa-trash"></i> Remove
</span>
</td>
</tr>
<?php
}
} else {
echo '<div class="alert alert-danger">No products in shopping cart!</div>';
}
?>

<tr>
<td></td>
<td></td>
<td></td>
<td align="right"><b>Total: $ Amount</b></td>
</tr>
</table>


So this rule calculates the price:

$line->total = ($lines->price*$cart[$i]["count"]);


But all the results from that line I want to be added up to a total price. Can someone help me with that?

Answer

Just add the product totals to a new variable.

When looping out the cart:

<?php
    $amount = 0;
    foreach($products as $product){
        $amount += $product->total;
?>

After the loop:

<td align="right"><b>Total: <?= $amount ?></b></td>