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

PHP如何检测session数组中CodicArt和Taglia均相同的重复商品项

问题原因

现有判断逻辑是分别验证「购物车所有条目中存在匹配的CodicArt」和「购物车所有条目中存在匹配的Taglia」两个独立条件,只要两个条件分别全局成立就会判定为重复,并没有校验同一个条目同时满足两个字段匹配的要求,因此只要购物车中曾经出现过对应CodicArt的任意商品,同时出现过对应Taglia的任意商品,哪怕不属于同一条目,也会误判为重复。

解决方案

方案1:遍历校验(逻辑清晰易维护)

逐一遍历购物车的每个条目,同时比对两个字段是否匹配,匹配到即判定为重复:

if($prodottocar['CodicArt'] != NULL ){
    $isDuplicate = false;
    foreach($_SESSION['carrello'] as $item){
        if($item['CodicArt'] == $prodottocar['CodicArt'] && $item['Taglia'] == $prodottocar['Taglia']){
            $isDuplicate = true;
            break;
        }
    }

    if($isDuplicate){
        echo '<script type="text/javascript">alert("Articolo duplicato");</script>';
    }else{
        array_push($_SESSION['carrello'], $prodottocar);
        echo '<script type="text/javascript">alert("Prodotto inserito");</script>';
    }
}

方案2:array_filter 过滤校验(代码更简洁)

通过array_filter过滤出同时匹配两个字段的条目,根据结果集长度判断是否存在重复:

if($prodottocar['CodicArt'] != NULL ){
    $matchedItems = array_filter($_SESSION['carrello'], function($item) use ($prodottocar){
        return $item['CodicArt'] == $prodottocar['CodicArt'] && $item['Taglia'] == $prodottocar['Taglia'];
    });

    if(count($matchedItems) > 0){
        echo '<script type="text/javascript">alert("Articolo duplicato");</script>';
    }else{
        array_push($_SESSION['carrello'], $prodottocar);
        echo '<script type="text/javascript">alert("Prodotto inserito");</script>';
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:36:03