购物车:删除不起作用

时间:2012-02-18 22:33:35

标签: php

我的购物车脚本“删除”有问题(是开关的情况)

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;
            $_SESSION['cart'] = $cart;
        }
        break;

示例:$ _SESSION ['cart'] = 1,2,1; 问题是,当客户购买两次相同的商品时,它会删除两者。我该如何解决?

2 个答案:

答案 0 :(得分:1)

这段剪辑可能有所帮助:

$items = explode(',',$cart);
$newcart = array();
$deleted = false;
foreach ($items as $item) {
  if (!$deleted && $_GET['id'] == $item) {
    $deleted = true;
    continue;
  }
  $newcart[] = $item;
}
print_r(implode(',',$newcart));

答案 1 :(得分:1)

您需要设置一个标志,例如:

$items = explode(',',$cart);
        $newcart = '';
        $flag = false;
        foreach ($items as $item) {
            if ($_GET['id'] == $item && $flag === false) { $flag = true; continue; }


                if ($newcart != '') {
                    $newcart .= ','.$item;
                } else {
                    $newcart = $item;
                }

        }
$cart = $newcart;