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

如何在PHP多维数组中检测product_id是否存在以实现购物车去重增量更新

实现方案

核心逻辑

  • 先获取本次提交商品的product_id
  • 校验该ID是否已存在于Session存储的商品列表中
  • 存在则直接更新对应商品的quantity数量字段
  • 不存在则将当前商品追加到商品列表

修正后完整代码

if (isset($_POST['action'])) {
    // 初始化Session商品存储数组
    if (!isset($_SESSION['products'])) {
        $_SESSION['products'] = [];
    }

    $current_product = $_POST;
    $current_pid = $current_product['product_id'];
    $product_exist = false;

    // 遍历匹配已有商品ID
    foreach ($_SESSION['products'] as $index => $item) {
        if ($item['product_id'] == $current_pid) {
            // 匹配成功,累加数量,也可根据需求直接覆盖为提交的新数量
            $_SESSION['products'][$index]['quantity'] = (int)$item['quantity'] + (int)$current_product['quantity'];
            $product_exist = true;
            break;
        }
    }

    // 无匹配商品则新增
    if (!$product_exist) {
        $_SESSION['products'][] = $current_product;
    }

    // 调试输出
    echo '<pre style="color:#fff;">';
    var_dump($_SESSION['products']);
    echo '</pre>';
}

array_column 简化写法

如果你想用array_column+array_search的方案简化遍历代码,可使用如下实现,你之前使用失败大概率是没有严格判断返回值:

if (isset($_POST['action'])) {
    if (!isset($_SESSION['products'])) {
        $_SESSION['products'] = [];
    }

    $current_product = $_POST;
    $current_pid = $current_product['product_id'];
    
    // 提取所有已存商品ID生成一维数组
    $exist_pids = array_column($_SESSION['products'], 'product_id');
    $match_key = array_search($current_pid, $exist_pids);

    if ($match_key !== false) {
        // 注意必须用!==判断,避免匹配到下标为0的商品时逻辑错误
        $_SESSION['products'][$match_key]['quantity'] = (int)$_SESSION['products'][$match_key]['quantity'] + (int)$current_product['quantity'];
    } else {
        $_SESSION['products'][] = $current_product;
    }

    echo '<pre style="color:#fff;">';
    var_dump($_SESSION['products']);
    echo '</pre>';
}

注意事项

  • 原代码中$_SESSION['product']属于冗余存储,可直接删除,不需要单独存储单次提交的商品
  • 如果需要同步更新已存在商品的价格、服务选项等其他字段,可在匹配成功的分支中补充对应赋值逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:18:01