I'm trying to create a shopping cart but I need help with arrays.

if(!isset($_SESSION["cart_array"])||count($_SESSION["cart_array"])<1){
		// RUN IF THE CART EMPTY OR NOT SET
		$_SESSION["cart_array"]=array(1=>array("item_id"=>$pid,"quantity"=>1, "item_size" => $size, "item_color" => $color)); //quantity => $quantity (can be applied)
	}else{
		// RUN IF THE CART  HAS AT LEAST ONE ITEM IN IT
		foreach($_SESSION["cart_array"] as $each_item){
			$i++;
			while(list($key,$value) = each($each_item)){
				if($key=="item_id" && $value==$pid ){//|| $key == "item_size" && $value == $size || $key == "item_color" && $key == $color
					// That item is in cart already so let's adjust its quantity using array_splice()
					array_splice($_SESSION["cart_array"],$i-1,1,array(array("item_id"=>$pid,"quantity"=>$each_item['quantity']+1))); //$quantity + 1 can also be applied
					$wasFound=true;
				} // close if condition
			} // close while loop
		} // close foreeach loop
		if($wasFound == false) {
			array_push($_SESSION["cart_array"],array("item_id"=>$pid,"quantity"=>1,"item_size" => $size, "item_color" => $color));
		}
	}

When a user adds an item to cart. its supposed to create a new array for each product and update the quantity if its the same product id. I got that going, but the problem is when I try to include size and color. When I try to add the same product but different size and color, it doesn't create a new array and it just adds a quantity to my cart and updates my size and color. Can someone help?

Thank you

Recommended Answers

All 2 Replies

Item in session as an array? Why not moving in OOP and know exactly what is happening?

Sorry can you explain further? I'm new to this.

Also, I was messing around with my code and if I do this:

if($key=="item_id" && $value==$pid && $key == "item_size" && $value == $size && $key == "item_color" && $key == $color ){

or

if($key=="item_id" && $value==$pid && $key == "item_size" && $value != $size && $key == "item_color" && $key != $color ){

It will set up as a new item and wont update the quantity even if I have added the same product with same color and size. But I'm still trying to figure out how to change quantity if its the same product with same color and size, and add as different item if its not.

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.