stevesimo Posted May 3, 2007 Share Posted May 3, 2007 Hi, I am trying to use some code which I have found in a tutorial to write my first shopping cart in PHP. The code has an example to delete an item from the basket or to add an item to the basket. However the code doesnt explain how to reduce a quantity in basket by 1. Here is the code to delete an item from the basket if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } Can anyone see what I need to do to reduce the quantity by 1. Also How would I prevent the problem of somebody trying to reduce a quantity if it is already 0? Quote Link to comment Share on other sites More sharing options...
taith Posted May 3, 2007 Share Posted May 3, 2007 try this... if($cart){ $items=explode(',',$cart); foreach($items as $item){ if($_GET['id'] != $item){ $newcart[]=$item; } } $cart=implode(','$newcart); } Quote Link to comment Share on other sites More sharing options...
stevesimo Posted May 3, 2007 Author Share Posted May 3, 2007 Hi, I have discovered that the cart contains a comma seperated list of product ids. So for example the cart 1,2,3,1,1,2 contains 3 of product 1, 2 of product 2, and 1 of product 3. Providing I know what the product id is and that the quantity is greater than 0, how would I reduce the string by 1? Quote Link to comment Share on other sites More sharing options...
stevesimo Posted May 3, 2007 Author Share Posted May 3, 2007 Fixed it using a long winded approach. //do a count of all items in the trolley if ($cart){ $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } } //initialise empty cart $tempcart = ""; //for each product in list foreach ($contents as $id=>$qty){ //is product in list equal to one being reduced if($id == $_GET['id'] && $qty > 0){ for($i=1;$i<$qty;$i++) //add all items - 1 $tempcart = $tempcart.$id.','; }else{ for($i=1;$i<=$qty;$i++) //add all items $tempcart = $tempcart.$id.','; } //trim final comma $cartlength = strlen($tempcart) - 1; $tempcart = substr($tempcart,0,$cartlength); } //set cart to tempcart $cart = $tempcart; Thanks for your help Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.