假设我有$_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['cart']数据:(
unset($_SESSION['cart'][$id2]);
您不需要在foreach中遍历整个数组。简单总比复杂好:)
为什么循环通过?如果你得到了你想删除的id作为一个参数,你可以这样做:
public function removeItem($id2) {
unset($_SESSION['cart'][$id2]);
}
如果您想清除id,只需执行:
$_SESSION['cart'][$id] = null;
希望这能帮助
只做
public function removeItem($id){
unset($_SESSION['cart'][$id]);
}