session_start();
$quantity=1;
$id=$_POST['id'];
$productByCode= Yii::app()->db->createCommand("SELECT * FROM products where id='".$id."'")->queryRow();
$itemArray = array($productByCode["id"]=>array('ItemName'=>$productByCode["ItemName"], 'id'=>$productByCode["id"], 'price'=>$productByCode["price"], 'quantity'=>$quantity));
if(!empty($_SESSION["cart_item"])) {
if(array_key_exists($productByCode["id"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode["id"] == $k)
$_SESSION["cart_item"][$k]["quantity"] += $quantity;
}
}
else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else {
$_SESSION["cart_item"] = $itemArray;
}
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["ItemName"]; ?></strong></td>
<td><?php echo $item["quantity"]; ?></td>
<td align=right><?php echo "$".$item["price"]; ?></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "$".$item_total; ?></td>
</tr>
</tbody>
</table>
<?php
}
我有上面的示例代码,当我们点击添加到购物车产品,在会话中存储n个商店时显示结果
Name Quantity Price
Banana 1 $50.00
Banana 1 $50.00
Banana 1 $50.00
Banana 1 $50.00
Banana 1 $50.00
Banana 1 $50.00
Total: $300
但我希望这样显示,当我们点击产品上的添加到购物车按钮时,只有数量增加不重复产品。
Name Quantity Price
Banana 6 $50.00
Total: $300
答案 0 :(得分:0)
试试这个,
<?php
$item_quantity = 0;
foreach ($_SESSION["cart_item"] as $item){
$item_name= $item["ItemName"];
$item_price= $item["price"];
$item_quantity +=$item["quantity"];
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td><strong><?php echo $item_name; ?></strong></td>
<td><?php echo $item_quantity; ?></td>
<td align=right><?php echo "$".$item_price; ?></td>
</tr>