问题
I am building a basic shopping cart. The cart is stored in a session uses product IDs.
I can add items and remove them.
If an item is added more than once, the cart is counting the multiple entries.
I am not sure how to change these quantities.
When exploding the cart session, it looks like this: 1,2,1,1
There is 3 x product 1 and 1 x product 1.
If I remove a product 1, it removes all the 1 IDs which is right.
But I'm not sure how to remove just 1 of them or set how many should be in there.
This is my processing code:
// 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;
Any ideas?
Thanks
Rob
回答1:
You should not be using a comma-delimited string to store your cart at all. Instead, $_SESSION['cart']
should be an array containing the quantities of products.
The structure of the array becomes $_SESSION['cart'][$product_id] = $quantity_in_cart
This allows you to increment/decrement quantities from the cart. When they reach 0, you can delete them entirely, if you wish. This is all far simpler to implement and keep track of than attempting to modify a comma-separated string as you are currently doing.
// 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]);
}
Then for free, you get an easy way to view item quantities:
// 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";
回答2:
When adding items to your cart, you could use a format like this:
$_SESSION['cart'][$productId] = $quantity
So, when adding a product
if (isset($_SESSION['cart'][$productId])
$_SESSION['cart'][$productId]++;
else
$_SESSION['cart'][$productId] = 1;
Removing, in this case, would simply be the reverse. Simply decrement the quantity for the product being removed.
来源:https://stackoverflow.com/questions/8128433/removing-values-from-php-session