2012-01-12 138 views
1

比方说,我有$ _SESSION ['cart'];当我打印此如何从会话数组中删除特定键=>值?

echo "<pre>",print_r($_SESSION['cart']),"</pre>"; 

它会显示类似

Array 
(
    [1] => 2 
    [2] => 2 
) 

,其中键是产品ID和值是每种产品的数量。 因此,如果我想删除产品号。 2从该会话数组中, 怎么办?

我想,来到我的脑海

public function removeItem($id2){ 
    foreach($_SESSION['cart'] as $id => $qty) { 
     if ($id == $id2){ 
     unset($_SESSION['cart'][$id]); 

     } 
    } 
} 

它删除了整个$ _SESSION [“购物车”]最快的功能数据:(

回答

4
unset($_SESSION['cart'][$id2]); 

你不需要在foreach中遍历整个数组。简单比复杂更好:)

+0

我想这一点,它去掉了特定的product .. but the last product remaining,can not be removed,why why ... – sasori 2012-01-12 11:12:52

+0

你的意思是说“不能被删除”是什么意思? – wikp 2012-01-13 14:38:26

1

如果你想清除ID只是做:

$_SESSION['cart'][$id] = null; 

希望这有助于

+0

它并没有帮助:( – sasori 2012-01-12 11:01:24

2

为什么你循环?如果你得到你想要做反正删除作为参数的ID,你可以这样做:

public function removeItem($id2) { 
    unset($_SESSION['cart'][$id2]); 
} 
0

只是做

public function removeItem($id){ 
    unset($_SESSION['cart'][$id]); 
}