【发布时间】:2015-08-01 14:28:07
【问题描述】:
我正在创建一个购物车。添加和删除项目功能的两个问题。添加购物车中已有的商品时,它不会覆盖现有商品,从而导致购物车中同一商品的两个实例。 删除项目仅适用于列表中最顶层的项目。
switch($_GET["action"])
{
case "add":
if(!empty($_POST["quantity"]))
{
$id=$_POST["id"];
$result = $mysqli->query("SELECT * FROM menu WHERE itemid='$id'");
while($itembyId=$result->fetch_assoc())
{
$itemArray = array($id=>array('name'=>$_POST["name"],
'id'=>$id, 'quantity'=>$_POST["quantity"], 'details'=>$_POST["details"],
'price'=>$_POST["price"]));
if(!empty($_SESSION["cart_item"]))
{
if(in_array($itembyId["itemid"],$_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $k => $v)
{
if($itembyId["itemid"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
}
else
{
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else
{
$_SESSION["cart_item"] = $itemArray;
}
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $k => $v)
{
if($_GET["id"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
【问题讨论】:
标签: php session-variables associative-array shopping-cart cart