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 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件