0

my goal is when user adds a product thats already in the cart, it will retain the product name and it will add 1 to the current quantity

my code is:

$item_found = false;

$index_of_array = 0;

if(isset($_POST['product_id']))
{
	$product_id = $_POST['product_id'];

	if(!isset($_SESSION['cart_array'] ) || empty($_SESSION['cart_array'] ))
	{
		$_SESSION['cart_array'] = array(1 => array("product_id" => $product_id, "quantity" => 1));
	}
	else
	{
		foreach($_SESSION['cart_array'] as $each_item)
		{
			$index_of_array++;
			
			while(list($key, $value) = each($each_item))
			{
				if($key == "product_id" && $value == $product_id)
				{
					array_splice($_SESSION['cart_array'], $index_of_array-1, 1, array(array("product_id" => $product_id, "quantity" => $each_item['quantity']+1)));
					$item_found = TRUE;
				}
			}
			if($item_found == FALSE)
			{
				array_push($_SESSION['cart_array'], array("product_id" => $product_id, "quantity" => 1));
			}
		}
	}
}
2
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by diafol
0

lets see if code will be more clear:

$item_found = false;
 
$index_of_array = 0;
 
if(isset($_POST['product_id']))
{
	$product_id = $_POST['product_id'];
 
	if(!isset($_SESSION['cart_array'] ) || empty($_SESSION['cart_array'] ))
	{
		$_SESSION['cart_array'] = array(1 => array("product_id" => $product_id, "quantity" => 1));
	}
	else
	{
		foreach($_SESSION['cart_array'] as $each_item)
		{
			$index_of_array++;
 
			while(list($key, $value) = each($each_item))
			{
				if($key == "product_id" && $value == $product_id)
				{
					array_splice($_SESSION['cart_array'], $index_of_array-1, 1, array(array("product_id" => $product_id, "quantity" => $each_item['quantity']+1)));
					$item_found = TRUE;
				}
			}
			if($item_found == FALSE)
			{
				array_push($_SESSION['cart_array'], array("product_id" => $product_id, "quantity" => 1));
			}
		}
	}
}
0

You could ask, but I doubt whether the mods/admins will do it. How about you post your solution and mark the thread solved.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.