【问题标题】:Update product quantity in php session array if item is already there如果项目已经存在,则更新 php 会话数组中的产品数量
【发布时间】:2013-05-20 22:26:56
【问题描述】:

我已经使用 php 实现了简单的购物车。我可以在购物车中添加产品并将其添加到数组中。我在 url 上获取我的产品 id,当我根据 thar url id 单击添加到购物车按钮时,我从数据库中获取产品数据并添加到会话数组,但我的问题是当我添加相同的产品时,我会在会话中获得新条目,而不是更新该产品的数量。 那么如果 produt_id 已经存在,我编写什么代码来更新购物车数量?

这是使用 $_SESSION['cart'] 的 print_r 数组值。

[cart] => Array
    (
        [0] => Array
            (
                [product-id] => 1
                [item] => mango
                [unitprice] => 20
                [quantity] => 1
            )
         [1] => Array
            (
                [product-id] =>2
                [item] => chickoo
                [unitprice] => 20
                [quantity] => 1
            )

    )

【问题讨论】:

    标签: php session cart


    【解决方案1】:

    听起来您需要确保product_id 不在您的会话数组中。试试下面的

    $found = false;
    foreach($_SESSION['cart'] as $product)
    {
        if($_REQUEST['product_id'] == $product['product_id']) {
            $found = true;
            break;
        }
    }
    
    if($found)
    {
        $_SESSION['cart'][$_REQUEST['product_id']]['quantity'] += 1;
    } else {
        // go get new product and add to $_SESSION['cart']
    }
    

    【讨论】:

    • 嘿,谢谢,它的工作原理....太棒了。我尝试了 2 天,但没有。你如何写出好的逻辑?请给我一些改进这种逻辑的提示我还有一个问题,而不是这个找到的变量,我们不能在每个循环中写它 if 条件吗?为什么我们使用 $found 变量?
    • 如果你愿意,你可以把它写在 for 循环中。我通常会尝试将其分开,以防出现其他逻辑,在我开始更改/操作数据的过程之前,我必须弄清楚有关数据的多项内容。
    猜你喜欢
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2012-06-23
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    相关资源
    最近更新 更多