Jump to content

Help with Array


Canman2005

Recommended Posts

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.