【问题标题】:Add and remove items from shopping cart using session variables使用会话变量在购物车中添加和删除商品
【发布时间】: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


    【解决方案1】:

    这对我有用! 这是增加数量的一个选项......

    <form action="xxxx" method="POST"><input type="hidden" name="type" value="update_suma" /><input type="hidden" name="id" value="'.$item["id"].'" /><input type="submit"value="+" /></form>
    
    
    <pre>case "update_suma":
            if(!empty($_SESSION["cart_item"])) {
                foreach($_SESSION["cart_item"] as $k => $v) {
                        if($_POST["identidad"] == $_SESSION["cart_item"][$k]['id'])
    
                           $_SESSION["cart_item"][$k]["cantidad"]++;    
    
                }
            }
    
    break;</pre>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2015-07-26
      相关资源
      最近更新 更多