PHP Sessions 购物车:如果产品已经标识了会话,则更新产品 [英] PHP Sessions shopping cart: update product if it's already id the session

查看:28
本文介绍了PHP Sessions 购物车:如果产品已经标识了会话,则更新产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力寻找一个带有 $_SESSION 的简单购物车的解决方案.我保持非常简单,这是我现在的代码

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) 如果 $_SESSION['cart'] 不存在,则创建它,否则添加新项目.2)当您将商品添加到购物车时,您必须为该商品选择尺寸和数量.3) 如果该商品已存在于购物车数组中,请检查大小是否相同,如果相同则更新数量.问题来了,如果项目已经存在(检查 $_SESSION['cart'][$id])但大小不同,不要更新当前的,而是创建一个新物品.问题是当前的一个被替换而不是添加一个,所以我只有最新的一个,而不是两个具有相同 id 但不同 size 的产品.

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 !

先谢谢你.

推荐答案

尝试使用大小作为多维数组中额外维度的键.您当前的代码只允许您为每件商品指定一个尺码.

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.

你会得到类似的结果:

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;
    }
}

这篇关于PHP Sessions 购物车:如果产品已经标识了会话,则更新产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆