因此,我有一个购物车系统,需要更新特定会话变量的数量。现在,如果我有一个ID = 1的商品并添加另一个ID = 1的商品,它将数量更新为2,这很好。但是,如果我添加一个ID = 2的项目,然后我再次添加另一个id = 1的项目,它将id = 2的数量更新为2什么时候应该将id的数量更新为1到3这是我的代码:$exists = false;foreach ($_SESSION['cart'] as $key => $item) { if ($item['product_id'] == $part_id) { $exists = true; }}if ($exists == true) { $_SESSION["cart"][$key]['quantity']++;}else{$_SESSION['cart'][] = array( 'product_id' => $part_id, 'title' => $title, 'price' => $price, 'default_img' => $default_img, 'quantity' => $quantity);}
1 回答
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
婷婷同学_
TA贡献1844条经验 获得超8个赞
在循环的最后,当您更新时$_SESSION["cart"][$key]['quantity'],$key它将始终指向中的最后一项$_SESSION["cart"],因此您将看到行为。您应该在循环中进行更新,例如
foreach ($_SESSION['cart'] as $key => $item) {
if ($item['product_id'] == $part_id) {
$exists = true;
$_SESSION["cart"][$key]['quantity']++;
}
}
或在找到匹配项时退出循环,从而$key指向正确的值:
foreach ($_SESSION['cart'] as $key => $item) {
if ($item['product_id'] == $part_id) {
$exists = true;
break;
}
}
- 1 回答
- 0 关注
- 116 浏览
添加回答
举报
0/150
提交
取消