提问者:小点点

更新多维购物车数组中的值


我正在用PHP编写一个自定义购物车,我将产品信息添加到购物车会话中,如下所示:

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

我的挑战是:如果产品已经存在于$\u SESSION['cart]数组中,我想更新产品的价格和数量($qty),而不是添加它。像这样的

price = price + $price,
qty = qty + $qty

共1个答案

匿名用户

此示例与您的示例类似。您可以在else条件下从foreach循环添加代码。我正在考虑product_id而不是$title变量。

 $_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);

更新产品前的输出:

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

在会话中添加新产品后的输出。

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