如何取消设置$ _SESSION数组中的项目
问题描述:
i have 2 functions. First one is adding item to cart, second should delete specific item based on product id.
function AddToCart($pid) {
if (isset($_SESSION['products']['prod_count'])) {
$_SESSION['products']['prod_count'] ++;
$incart = $_SESSION['products']['prod_count'];
$_SESSION['products'][$incart]['product_id'] = $pid;
} else {
$_SESSION['products']['prod_count'] = 0;
$incart = $_SESSION['products']['prod_count'];
$_SESSION['products'][$incart]['product_id'] = $pid;
}
}
function DeleteProduct($pid) {
foreach ($_SESSION['products'] as $key => $my_value) {
foreach ($my_value as $key => $product_id) {
if ($product_id == $pid) {
// do not know how to unset this product
}
}
}
}
I need some idea on how to unset the product if $product_id == $pid or may be some other ideas how to achieve that.
My array look something like:
array(1) { ["products"]=> &array(4)
{ ["prod_count"]=> int(2)
[0]=> array(1) { ["product_id"]=> int(4)}
[1]=> array(1) { ["product_id"]=> int(10) }
[2]=> array(1) { ["product_id"]=> int(11) } } }
答
The following code would simply solve your problem:
function DeleteProduct($pid) {
foreach ($_SESSION['products'] as $key => $product) {
if ($pid === $product['product_id']) {
unset($_SESSION['products'][$key]);
}
}
}
But to make your work alot easier in the future you could also build your array like this:
$_SESSION['products'] = array(
'product_id' => 'amount',
);
To add a product you would simply do:
$_SESSION['products'][$product_id] += $amount;
To count your products you could use:
count($_SESSION['products']);
Here is a simple example of what your functions could be like:
function addProduct($pid, $value = 1) {
$_SESSION['products'][$pid] += $value;
}
function removeProduct($pid) {
unset($_SESSION['products'][$pid]);
}
function countProducts() {
return count($_SESSION['products']);
}
Good luck!