dssqq64884 2018-06-30 07:02
浏览 44
已采纳

更新多维购物车阵列中的值

I am writing a custom shopping cart in PHP, I add product info to the cart session like this:

$product_array=array($title,$price,$qty);
if(!isset($_SESSION['cart']))
$_SESSION['cart']=array();

if(!in_array($product_array,$_SESSION['cart']))
$_SESSION['cart'][]=$product_array;
else
{
// update price and quantity here
}

My challenge: I want to update the price and quantity($qty) of the product if it already exists in $_SESSION['cart'] array rather than adding it. Something like this

price = price + $price,
qty = qty + $qty
  • 写回答

1条回答 默认 最新

  • dongxu2398 2018-06-30 07:17
    关注

    This example is similar to your example. you can add code from foreach loop in else condition. I am considering product_id instead of $title variable.

     $_SESSION['cart'][] = [ 'product_id'=> 12, 'price' => 100 , 'quantity' => 2 ];
     $_SESSION['cart'][] = [ 'product_id'=> 11, 'price' => 200, 'quantity' => 3 ];
    
        $product_array = ['product_id' => 11, 'price'=> 200, 'quantity' => 4 ];
        foreach( $_SESSION['cart'] as $key => $value ) {
          if( $value['product_id']  == $product_array['product_id']) {
             $_SESSION['cart'][$key]['quantity'] = $value['quantity'] + $product_array['quantity'];
               $_SESSION['cart'][$key]['price'] = $value['price'] + $product_array['price'];
            }
        }
    print_r($_SESSION);
    

    Output before updating product :

    Array
    (
        [cart] => Array
            (
                [0] => Array
                    (
                        [product_id] => 12
                        [price] => 100
                        [quantity] => 2
                    )
                [1] => Array
                    (
                        [product_id] => 11
                        [price] => 200
                        [quantity] => 3
                    )
            )
    )
    

    Output after adding new product in session.

    Array
    (
        [cart] => Array
            (
                [0] => Array
                    (
                        [product_id] => 12
                        [price] => 100
                        [quantity] => 2
                    )
                [1] => Array
                    (
                        [product_id] => 11
                        [price] => 400
                        [quantity] => 7
                    )
            )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备