【发布时间】:2015-10-23 21:05:08
【问题描述】:
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
【问题讨论】:
标签: javascript php jquery ajax session