我正在制作一个购物车,实际上它现在几乎已经完成了。我只想计算总价。问题是,每个产品的价格是在foreach循环中计算的(价格*数量),所以我不确定如何将所有价格加起来。
PHP函数:
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;
}
我如何全部显示:
<?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; ?>
<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>
所以这条规则计算价格:
$line->total = ($lines->price*$cart[$i]["count"]);
但是,我希望将该行的所有结果加到总价中。有人可以帮我吗?
答案 0 :(得分:1)
只需将产品总数添加到新变量中即可。
循环推车时:
<?php
$amount = 0;
foreach($products as $product){
$amount += $product->total;
?>
循环之后:
<td align="right"><b>Total: <?= $amount ?></b></td>
答案 1 :(得分:1)
您可以只添加一个新变量,将以前的价格相加并将此变量添加到$cartArray
:
public function getCart(){
$cartArray = array();
$cartArray["products"] = array();
$totalCart = 0;
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"]);
$totalCart += $line->total;
$cartArray["products"][] = $line;
}
}
}
$cartArray["total"] = $totalCart;
return $cartArray;
}
这将返回如下数组:
Array(
"products" => Array(
[0] = ...
[1] = ...
),
"total" => 300
);