Updating Values in A Multidimensional Cart Array


Updating Values in A Multidimensional Cart Array



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 Answer
1



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
)
)
)





Thanks. Is there a way I can just update the concerned elements within the multidimensional array without looping through it? I already know that those elements exist there.
– bodesam
Jun 30 at 12:04





And what of the case that the product is NOT in the cart session. How would you state $_SESSION['cart']
– bodesam
Jun 30 at 15:01





I already mentioned that add my code in else condition. If product is not in cart then your if condition will work
– Shivrudra
Jun 30 at 15:40





I have another way of implement cart functionality. You can add key as product id & quantity as value against that product key. You can try in that way. If you can't find solution, I will provide you code for same.
– Shivrudra
Jun 30 at 15:44






If you implement with above logic then you don't need to add for loop while adding product in cart
– Shivrudra
Jun 30 at 15:56






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

.

How to generate build files in next js

Delphi Android file open failure with API 26