数量不更新

Qty not updating

我正在尝试设置基本的购物车会话并添加产品。除了添加相同的项目外,我的一切都正常,它不会持续更新数量。

我注意到,如果我只在数组中添加一种产品并尝试再次添加相同的产品,它确实会增加。但是一旦有 2 个或更多不同的产品,添加一个现有的产品不会更新数量,而是在数组中添加一个完整的条目。

我建议更改购物车的结构:而不是像

那样只是将产品添加到购物车
$shopping_cart[] = Array
            (
                "productid" => $productId,
                "name" => "Fish Food",
                "quantity" => "3",
                "price" => "3.00",
                "weight" => "500g packet"
            );

这样添加:

$shopping_cart[$productId] = Array
            (
                "productid" => $productId,
                "name" => "Fish Food",
                "quantity" => "3",
                "price" => "3.00",
                "weight" => "500g packet"
            );

以后您可以使用 isset($shopingcart[$product_id]) 或其他数组函数来检查产品是否在购物车中。

原因是当您使用 array_merge 合并时。它只会接受元素,而不是键。

if(!empty($_POST["p_quantity"])) {
                $productById = queryFunc("SELECT * FROM products WHERE product_id='" . $_GET["prid"] . "'");


                $productArray = array('productid'=>$productById[0]["product_id"], 'name'=>$productById[0]["product_name"], 'quantity'=>$_POST["p_quantity"], 'price'=>$productById[0]["unit_price"], 'weight'=>$productById[0]["unit_quantity"]);

                if(!empty($_SESSION["shopping_cart"])) {
                    if(in_array($productById[0]["product_id"],array_keys($_SESSION["shopping_cart"]))) {
                        foreach($_SESSION["shopping_cart"] as $keys => $values) {
                                if($productById[0]["product_id"] == $keys) {
                                    if(empty($_SESSION["shopping_cart"][$keys]["quantity"])) {
                                        $_SESSION["shopping_cart"][$keys]["quantity"] = 0;
                                    }
                                    $_SESSION["shopping_cart"][$keys]["quantity"] = $_SESSION["shopping_cart"][$keys]["quantity"] + $_POST["p_quantity"];
                                }
                        }
                    } else {
                        $_SESSION["shopping_cart"][$productById[0]["product_id"]] = $productArray;
                    }
                } else {
                    $_SESSION["shopping_cart"] = array();
                    $_SESSION["shopping_cart"][$productById[0]["product_id"] = $productArray;
                }
            }