Canman2005 Posted March 29, 2010 Share Posted March 29, 2010 Hi all I have a small shopping cart system using an array to store product id numbers in. It stores it like 2,34,55,55,67,121 Within my cart I have the following, which allows the quantity of a particular product ID to be increased if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; To use the above, I have a input field next to each item which looks like <input type="text" name="qty23" value="" /> How can I adapt the above code so that if I pass in my URL ?action=update&id=23 then it would reduce the quantity of 23 by 1 so with an array which looked like 10,10,23,23,30 after passing ?action=update&id=23 it would then look like 10,10,23,30 any help would be great, been trying to crack this but with no luck thanks in advance ed Link to comment https://forums.phpfreaks.com/topic/196911-help-with-array/ Share on other sites More sharing options...
nicholasstephan Posted March 29, 2010 Share Posted March 29, 2010 That's the weirdest way to store quantities dude... take a look at the php array functions (http://us.php.net/manual/en/ref.array.php) you've got, you should be able to figure something out. But I'd recommend that to turn your array into something more like: $cart = array( '2' => '1', // id => quantity '34' => '1', '55' => '2', '67' => '1', '101' => '1' ); Then all you'd have to do to increase a value in the array is: $cart[$id]++; Also - look into making your <input/> tags arrays too to save yourself all that string manipulation: Instead of having the input be named "qty23" you could name it "qty[23]"... then in php it's simply $_POST['qty']['23']... Then you could update your quantities like: foreach($_POST['qty'] as $id => $qty) $cart[$id] = $qty; Link to comment https://forums.phpfreaks.com/topic/196911-help-with-array/#findComment-1033816 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.