I try to add product to the shopping cart but I have some problems with the loop logic. This function should add new product and check if product id is already in the cart. If it is in the cart it should add 1 to existing product or the quantity selected by user. Here is some code that I have:
function AddToCart($pid, $q)
{
$quantity = $q;
$product_id = $pid;
if (is_array($_SESSION['products']))
{
foreach($_SESSION['products'] as $key => $my_value)
{
if ($pid === $my_value['product_id'])
{
if ($quantity != 1)
{
$quantity = $my_value['quantity'] + $quantity;
$_SESSION['products'][$key]['quantity'] = $quantity;
}
else
{
$quantity = $my_value['quantity'] + 1;
$_SESSION['products'][$key]['quantity'] = $quantity;
}
}
else
{
$_SESSION['products'][] = array(
'product_id' => $product_id,
'quantity' => $quantity,
);
}
}
}
else
{
$_SESSION['products'][] = array(
'product_id' => $product_id,
'quantity' => $quantity,
);
}
}
the var_dump of the $_SESSION will be the following:
array(8) {
[0]=> array(2) { ["product_id"]=> int(4) ["quantity"]=> int(1) }
[1]=> array(2) { ["product_id"]=> int(10) ["quantity"]=> int(1) }
[2]=> array(2) { ["product_id"]=> int(11) ["quantity"]=> int(2) }
[3]=> array(2) { ["product_id"]=> int(11) ["quantity"]=> int(3) }
[4]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(2) }
[5]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(3) }
[6]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(4) }
[7]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(5) } }
Although I add only 4 products: id 4, 10, 11 and 12