duandongji2231 2015-06-23 17:11
浏览 86

将多个产品添加到购物车

I have some problem with the logic and any help would be appreciated:

$total_add = $_POST['xTotalNumProduct'];

if(ISSET($_SESSION['cart']['CartTotalNum']) && $_SESSION['cart']['CartTotalNum'] > 0) {
    $CartTotalNum = $_SESSION['cart']['CartTotalNum'];
    $cart = $_SESSION['cart'];

    for ($i=1; $i<=$total_add; $i++) {

        for ($x=1; $x<=$CartTotalNum; $x++) {
            if ($cart['ItemId'.$x] == $_POST['xPdt'.$i.'Id']) { // this will only check the first key ie $cart['ItemId1]
                $cart['ItemQty'.$x] = $_POST['xPdt'.$i.'Qty'];
            }
            else {
                $CartTotalNum = $CartTotalNum + 1;
                $cart['ItemId'.$CartTotalNum] = $_POST['xPdt'.$i.'Id'];
                $cart['ItemQty'.$CartTotalNum] = $_POST['xPdt'.$i.'Qty'];
            }
        }
    }
    $cart['CartTotalNum'] = $CartTotalNum;

} else {
    $cart = array();
    for ($i=1; $i<=$total_add; $i++) {
        $cart['ItemId'.$i] = $_POST['xPdt'.$i.'Id'];
        $cart['ItemQty'.$i] = $_POST['xPdt'.$i.'Qty'];      
    }
    $cart['CartTotalNum'] = $total_add;
}

The problem with the above script is that it only checks the $cart['ItemId1] and if not equal it will add to cart without checking $cart['ItemId2], $cart['ItemId3] etc.

How can I fix that?

  • 写回答

2条回答 默认 最新

  • dongsaohu6429 2015-06-23 17:15
    关注

    This is incredibly bad code:

                $cart['ItemQty'.$x] = $_POST['xPdt'.$i.'Qty'];
                              ^^^^^
    

    Why build dynamic keys? You can use a multi-dimensional arrays quiet easily:

       $_SESSION['cart'][$itemID]['quantity'] = $_POST[...];
    

    Keying your cart by the itemID allows all of the item's cart data to be kept in one place, instead of scattered everywhere.

    And note that similar constructs can be used in your form field names, e.g.

    <input type="text" name="foo[bar][baz][42]" ... >
    

    would give you

    $_REQUEST['foo']['bar']['baz'][42]
    

    to work with when the form's submitted.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等