2012-02-18 17 views
0

になって、私は私のショッピングカートスクリプトの「削除」といくつかの問題は、(スイッチの場合)で抱えている動作しませんショッピングカート:削除

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

はあなたが*正確に*どこうまくいかないものを明確にすることはできますか? –

+0

私はそれを下に置いています:削除すると、同じIDを持つすべてのアイテムを削除します(クライアントが同じものを2回購入した場合、2回削除します) – chenci

答えて

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; 
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)); 
+0

はい!魅力のように働く。ありがとう、私はこの方法をより良い作品を新しいカートを構築参照してください。 – chenci

関連する問題