You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Laravel中如何更新购物车数组内已存在product_id对应的商品数量

解决方案

原有代码存在两个核心问题:

  • 解析Cookie内容时写法错误,会导致购物车数组多嵌套一层结构
  • 缺少已存在商品的判断逻辑,每次都直接往数组末尾追加新元素

修正后可正常运行的代码如下:

// 初始化购物车数组
$cart_array = [];
$get_cart = Cookie::get('user_cart');
if (isset($get_cart)) {
    // 第二个参数true 强制返回关联数组,避免返回对象导致访问报错
    $cart_array = json_decode($get_cart, true);
}

$target_product_id = $request->product_id;
$target_quantity = $request->quantity;
$product_exist = false;

// 遍历已有购物车判断商品是否存在
foreach ($cart_array as &$item) {
    if ($item['product_id'] === $target_product_id) {
        // 存在则累加数量,如果业务需要直接覆盖提交的数量,改成 = $target_quantity 即可
        $item['quantity'] = (int)$item['quantity'] + (int)$target_quantity;
        $product_exist = true;
        break;
    }
}
// 解除引用避免后续操作出现意料外的异常
unset($item);

// 商品不存在则新增到购物车数组
if (!$product_exist) {
    $cart_array[] = [
        "product_id" => $target_product_id,
        "quantity" => $target_quantity
    ];
}

// 写入Cookie
$cart_json = json_encode($cart_array);
$cart_cookies = Cookie::forever('user_cart', $cart_json);

内容的提问来源于stack exchange,提问作者Catto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 14:45:03