2011-11-14 128 views
1

我正在構建基本購物車。購物車存儲在會話中使用產品ID。從PHP會話中刪除值

我可以添加項目並將其刪除。

如果一個項目被多次添加,購物車正在對多個條目進行計數。

我不知道如何更改這些數量。

當爆炸的車會話,它看起來像這樣:1,2,1,1

有3×1產品和1個產品1

如果我刪除產品1,它刪除所有正確的ID。

但我不知道如何刪除其中的一個或設置多少應該在那裏。

這是我的處理代碼:

// Process actions 
$cart = $_SESSION['cart']; 
@$action = $_GET['action']; 
switch ($action) { 
case 'add': 
    if ($cart) { 
     $cart .= ','.$_GET['id']; 
    } else { 
     $cart = $_GET['id']; 
    } 
    break; 
case 'delete': 
    if ($cart) { 
     $items = explode(',',$cart); 
     $newcart = ''; 
     foreach ($items as $item) { 
      if ($_GET['id'] != $item) { 
       if ($newcart != '') { 
        $newcart .= ','.$item; 
       } else { 
        $newcart = $item; 
       } 
      } 
     } 
     $cart = $newcart; 
    } 
    break; 
$cart = $newcart; 
break; 
} 
$_SESSION['cart'] = $cart; 

任何想法?

感謝

羅布

回答

3

你不應該使用逗號分隔的字符串存儲您的購物車都可以。相反,$_SESSION['cart']應該是包含產品數量的數組。

陣列的結構變得$_SESSION['cart'][$product_id] = $quantity_in_cart

這允許您從車遞增/遞減量。當他們達到0時,你可以完全刪除它們,如果你願意。這與實現目前所做的修改逗號分隔字符串相比,實現和跟蹤起來要簡單得多。

// Initialize the array 
$_SESSION['cart'] = array(); 

// Add product id 1 
// If the array key already exists, it is incremented, otherwise it is initialized to quantity 1 
$_SESSION['cart'][1] = isset($_SESSION['cart'][1]) ? $_SESSION['cart'][1]++ : 1; 
// Add another (now it has 2) 
$_SESSION['cart'][1] = isset($_SESSION['cart'][1]) ? $_SESSION['cart'][1]++ : 1; 
// Remove one of the product id 1s 
$_SESSION['cart'][1]--; 

// Add product id 3 
$_SESSION['cart'][3] = isset($_SESSION['cart'][3]) ? $_SESSION['cart'][3]++ : 1; 


// Delete the item if it reaches 0 (optional) 
if ($_SESSION['cart'][1] === 0) { 
    unset($_SESSION['cart'][1]); 
} 

那麼對於免費,你會得到一個簡單的方法來查看物品數量:

// How many product 2's do I have? 
$prod_id = 2; 
echo isset($_SESSION['cart'][$prod_id]) ? $_SESSION['cart'][$prod_id] : "You have not added this product to your cart"; 
+0

啊,我不知道你可以將數組存儲在那裏,我將列表分解成一個數組,所以這個工作更好。我能夠使用大部分讀取會話的其他代碼。謝謝 – Greybeard

2

當將項目添加到您的購物車,你可以使用的格式如下:

$_SESSION['cart'][$productId] = $quantity 

所以,在添加產品時

if (isset($_SESSION['cart'][$productId]) 
    $_SESSION['cart'][$productId]++; 
else 
    $_SESSION['cart'][$productId] = 1; 

在這種情況下,刪除將完全相反。簡單地減少被刪除產品的數量。

+0

感謝您的支持!與上面的評論一起使用它有助於獲得它。乾杯 – Greybeard