doukuilian8365 2014-03-28 14:54
浏览 17
已采纳

PHP Sessions购物车:如果产品已经是会话,则更新产品

I have struggled to find a solution to a simple shopping cart with $_SESSION. I kept it very simple and this is my code right now

if ( Input::isPost('add') ) {

    $id = Input::get('id');
    $qta = Input::post('qta');
    $size = Input::post('size');

    if ( !isset($_SESSION['cart']) ) {
        $_SESSION['cart'] = array();
    }

    if ( array_key_exists($id, $_SESSION['cart']) ) {
        if ( $_SESSION['cart'][$id][0] == $size ) {
            $_SESSION['cart'][$id][1]+=$qta;
        } else {
            $_SESSION['cart'][$id] = array( $size, $qta );
        }
    } else {
        $_SESSION['cart'][$id] = array( $size, $qta );
    }

}

So, what this code does ?

1) If the $_SESSION['cart'] does not exist, create it, otherwise add the new item. 2)When you add to cart a item, you must choose a size and a quantity for that item. 3) If that item already exists in the cart array, check if the size is the same, if so just update the quantity. Here is the problem, if the item already exists(checks for the $_SESSION['cart'][$id]) BUT the size is different, do not update the current one, but instead create a new item. The problem is that the current one is being replaced instead of adding one, so instead of 2 products with the same id but different size, I only have the most recent one.

If you could help me solve it I'll be very thankful !

Thank you in advance.

  • 写回答

4条回答 默认 最新

  • dongqiang1226 2014-03-28 15:05
    关注

    Try using the size as a key to an extra dimension in your multidimensional array. Your current code only allows you to have one size per item.

    You would end up with something like:

    if ( Input::isPost('add') ) {
    
        $id = Input::get('id');
        $qta = Input::post('qta');
        $size = Input::post('size');
    
        if ( !isset($_SESSION['cart']) ) {
            $_SESSION['cart'] = array();
        }
    
        if ( array_key_exists($_SESSION['cart'][$id][$size]) ) {
            $_SESSION['cart'][$id][$size] += $qta;
        } else {
            $_SESSION['cart'][$id][$size] = $qta;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条