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

时间:2013-06-17 00:58:31

标签: php html session shopping-cart

大家好,所以我设法得到我购物车中所有商品的小计,而不是堆叠溢出用户KyleK。我遇到问题的最后一个功能是,如果该项目已经退出,则将1添加到购物车中特定商品的数量。如果我点击添加到篮子两次,那么同一项目将被列出两次。相反,如果有意义的话,将项目列为一次,数量为2,那将是很好的。

提前谢谢你。

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

My Code

1 个答案:

答案 0 :(得分:0)

以下是您需要修改以执行所需操作的代码块:

//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;
}
相关问题