如果购物车中已经存在商品,则更新数量


Updating the quantity if item already exists in cart

大家好,所以我设法得到了我的购物车中所有项目的小计,感谢堆栈溢出用户KyleK。我遇到问题的最后一个功能是在购物车中添加1到特定项目的数量,如果该项目已经存在。目前,如果我点击两次添加到购物篮,那么同样的商品会被列出两次。相反,如果有意义的话,最好只列出一次,数量为2。

提前感谢。

我的代码位于堆栈溢出处。

代码

这是你需要修改的代码块,以便做你想做的:

//Add an item only if we have the threee required pices of information: name, price, qty
if (isset($_GET['add']) && isset($_GET['price']) && isset($_GET['qty'])){
        //Adding an Item
        //Store it in a Array
        $ITEM = array(
                //Item name            
                'name' => $_GET['add'],
                //Item Price
                'price' => $_GET['price'],
                //Qty wanted of item
                'qty' => $_GET['qty']          
                );
        //Add this item to the shopping cart
        $_SESSION['SHOPPING_CART'][] =  $ITEM;
        //Clear the URL variables
        header('Location: ' . $_SERVER['PHP_SELF']);
}

如果你点击"添加"两次,你只是运行这段代码两次。如果希望拥有一个"智能"购物车,则需要修改这部分代码,以包含对现有购物车项目的检查。如果传入的项已经存在,则增加该项的数量值。如果不存在,则将其作为新商品添加到购物车中。

$addItem = $_GET['add'];
$itemExists = checkCartForItem($addItem, $_SESSION['SHOPPING_CART']);
if ($itemExists){
     // item exists - increment quantity value by 1
     $_SESSION['SHOPPING_CART'][$itemExists]['qty']++;
} else {
     // item does not exist - create new item and add to cart
     ...
}
// Then, add this code somewhere toward the top of your code before your 'if' block
function checkCartForItem($addItem, $cartItems) {
     if (is_array($cartItems)){
          foreach($cartItems as $key => $item) {
              if($item['name'] === $addItem)
                  return $key;
          }
     }
     return false;
}