I'm facing an issue in a multi dimensional array. I need to change the quantity of a specific product set in session if both ID and variants of the selection are the same of one of session product, and increment by 1 this product.
the product I'm posting $newproduct
Array
(
[id] => 2
[title] => Vewlix 1080p (red and white)
[image] => amazing-modern-villa-Freshome-02.jpg
[variants] => Array
(
[0] => Array
(
[id] => 2
[option_name] => Panel 2 players (+50 euros)
[option_price] => 50.00
)
)
[quantity] => 1
[unit_price] => 1950.00
[price] => 2000
)
Here is my $_SESSION['shopping_cart']
:
Array
(
[0] => Array
(
[id] => 2
[title] => Vewlix 1080p (red and white)
[image] => amazing-modern-villa-Freshome-02.jpg
[variants] => Array
(
[0] => Array
(
[id] => 1
[option_name] => Panel 1 player
[option_price] => 0.00
)
)
[quantity] => 2
[unit_price] => 1950.00
[price] => 1950
)
[1] => Array
(
[id] => 2
[title] => Vewlix 1080p (red and white)
[image] => amazing-modern-villa-Freshome-02.jpg
[variants] => Array
(
[0] => Array
(
[id] => 2
[option_name] => Panel 2 players (+50 euros)
[option_price] => 50.00
)
)
[quantity] => 1
[unit_price] => 1950.00
[price] => 2000
)
)
The code:
$products_in_cart = array_column($_SESSION["shopping_cart"], "id");
$key = array_search($newproduct["id"], $products_in_cart);
if ($key !== false) {
$variants_in_cart = array_column($_SESSION["shopping_cart"][$key]["variants"], "id");
$new_variants = array_column($newproduct["variants"], "id");
sort($variants_in_cart);
sort($new_variants);
if (count(array_diff($variants_in_cart, $new_variants)) === 0) {
$_SESSION["shopping_cart"][$key]["quantity"] += 1;
} else {
$_SESSION["shopping_cart"][] = $newproduct;
}
} else {
$_SESSION["shopping_cart"][] = $newproduct;
}
For now I have the ID and variants comparaison working, but when similiar product is posted, instead of incrementing only the specific product with same id/variants, it increments all products quantities of my session by +1.
How can I add +1 only to the product with exact same ID / variants only ? I think my [$key] doesn't work, as it should be the filter to only increment the proper product quantity