无法在购物车中删除会话数组中的项目


Cant remove item with session array in shopping cart

我有一个购物车的会话数组,但问题是当我试图用UNSET命令删除所选项目时,它似乎不起作用。谁来帮帮我。我喜欢根据产品ID和尺寸删除商品,因为我购物车中的其他商品可能具有相同的产品ID,但尺寸不同。下面是我的代码:

购物车会话结构:

$_SESSION['cart_items'][$id.'-'.$size] = array('id'=> $id,'code' => $code, 'Quantity' => $quantity, 'Size' => $size);

delete item的编码:

    $size = $_GET['Product_Size'];
$id = $_GET['Product_ID'];
echo $id.$size;
if(!isset($_SESSION['cart_items'])){
    echo "<script type='text/javascript'>alert('Shopping list is empty!');
        window.history.back();</script>";   
}
if (isset($_SESSION['cart_items'])) {
    //print_r($_SESSION['cart_items']);
    foreach ($_SESSION['cart_items'] as $key => $value) {
    if ($key == $id.'-'.$size) {
        unset($_SESSION['cart_items'][$key]);
    //print_r($_SESSION['cart_items']);
        echo "<script type='text/javascript'>alert('Successful remove!');
        window.history.back();</script>";   
        break;  
                                                         }
    else
        {
        echo "<script type='text/javascript'>alert('Not found!');
        window.history.back();</script>";     
        }    
                                                        }
}

foreach循环语法中,您犯了一个逻辑错误,$_SESSION['cart_items']的内容是一个具有一些键和值的数组,键是$id-$size格式的,值是包含更多信息的数组。所以"键"是你应该检查的,修改代码如下:

foreach ($_SESSION['cart_items'] as $key => $value) {
    if ($key == $id.'-'.$size) {
        unset($_SESSION['cart_items'][$key]);
        // ... (the rest of the code)