0

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

先感谢您。

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

我的代码

4

1 回答 1

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;
}
于 2013-06-17T03:48:15.780 回答