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

PHP开发蛋糕店购物车时商品重复加入数组问题如何解决

问题排查

你的代码存在两个核心错误导致重复校验失效:

  1. 字段名拼写错误:表单提交的商品名参数是$_POST['cakename'],但校验时错误写为$_POST['cake_name'],多余的下划线导致拿到的参数为空,校验逻辑直接不生效
  2. in_array()使用场景错误:$_SESSION['cart']是二维数组,每个元素是包含商品信息的子数组,直接传入商品名字符串无法匹配到子数组内的cakename字段值
修复后的代码
<?php
session_start();
if(isset($_POST['add_to_cart']))
{
    $current_cake = $_POST['cakename'];
    $current_price = $_POST['cakeprice'];
    $item_exists = false;

    // 购物车未初始化
    if(!isset($_SESSION['cart']))
    {
        $_SESSION['cart'][0] = array(
            'cakename' => $current_cake,
            'cakeprice' => $current_price,
            'Quantity' => 1
        ); 
        echo "<script>
        alert('Item Added');
        window.location.href='index.php';
        </script>";
        exit();
    }

    // 遍历购物车校验是否已存在同款商品
    foreach($_SESSION['cart'] as $key => $item) {
        if($item['cakename'] == $current_cake) {
            $item_exists = true;
            // 可选:如果需要重复添加时叠加数量,替换下面的提示逻辑为
            // $_SESSION['cart'][$key]['Quantity'] +=1;
            // alert内容改成商品数量已更新即可
            break;
        }
    }

    if($item_exists) {
        echo "<script>
        alert('Item ALREADY Added');
        window.location.href='index.php';
        </script>";
        exit();
    }

    // 商品不存在则新增到购物车
    $count = count($_SESSION['cart']);
    $_SESSION['cart'][$count] = array(
        'cakename' => $current_cake,
        'cakeprice' => $current_price,
        'Quantity' => 1
    );       
    echo "<script>
    alert('Item Added');
    window.location.href='index.php';
    </script>";
    exit();
}
?>
优化说明
  • 统一了所有商品名字段的拼写,避免参数获取错误
  • 替换原错误的in_array()校验逻辑,改为遍历购物车逐行匹配商品名
  • 新增了exit()防止脚本后续逻辑意外执行
  • 保留了可选的数量叠加逻辑注释,可根据业务需求自行开启

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:06:03