为了账号安全,请及时绑定邮箱和手机立即绑定

如何更新特定会话的会话变量

如何更新特定会话的会话变量

PHP
jeck猫 2021-05-14 14:19:14
因此,我有一个购物车系统,需要更新特定会话变量的数量。现在,如果我有一个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 回答

?
婷婷同学_

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;

    }

}


查看完整回答
反对 回复 2021-05-28
  • 1 回答
  • 0 关注
  • 116 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信