简体   繁体   English

如果项目已经存在,则更新php会话数组中的产品数量

[英]Update product quantity in php session array if item is already there

I have implemented simple shopping cart using php.I can add product in cart and it adds to array.i Get my product id on url,when i click add to cart button based on thar url id i fetch product data from database and add to session array,but my problem is when i add same product i get new entry in session and the instead of updating quantity of that product. 我已经使用php实现了一个简单的购物车。我可以在购物车中添加产品并将其添加到array.i当我基于这些URL ID单击添加到购物车按钮时,我从URL获取我的产品ID,然后从数据库中获取产品数据并添加到会话数组,但是我的问题是,当我添加相同的产品时,我在会话中获得了新条目,而不是更新该产品的数量。 So what code i write to update the cart quantity if produt_id already there.? 那么如果produt_id已经存在,我会写什么代码来更新购物车数量呢?

This is print_r array value using $_SESSION['cart'] . 这是使用$_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
            )

    )

Sounds like you need to make sure the product_id isn't already in your session array. 听起来您需要确保product_id不在会话数组中。 Try the following 尝试以下

$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']
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM