Forum Moderators: coopster

Message Too Old, No Replies

array problem

         

terencepae

6:34 pm on Oct 23, 2007 (gmt 0)

10+ Year Member



Hey guys,

I made a small shopping cart function that adds/removes item in a session array.

It adds/removes items perfectly inside the session, but when I try to display it out I tried something like

$count = count($_SESSION['cart']);

and made a for loop $i = 0; $i < $count; $i++ and displayed things out.

Problem is, when I completely remove an item in between, then the keys doesn't get rearranged, so the loop doesn't really work.

Example would be..

Add 2 socks
Add 3 tires
Add 2 shoes

would give me
[0] => 2 socks
[1] => 3 tires
[2] => 2 shoes

and loop would just go through 0 through 2.

but if i take 3 tires out..

[0] => 2 socks
[2] => 2 shoes

booom! its broken.
I tried:


while(list($key, $val) = each($cart)) {
displayItem($cart['item'][$key], $cart['qty'][$key]);
}

didn't work..

Any suggestions?

dreamcatcher

6:39 pm on Oct 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Maybe test that the key exists in the loop?

while(list($key, $val) = each($cart)) {
if (isset($cart['item'][$key])) {
displayItem($cart['item'][$key], $cart['qty'][$key]);
}
}

dc

PHP_Chimp

7:06 pm on Oct 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could sort [uk2.php.net] the array

d40sithui

7:57 pm on Oct 23, 2007 (gmt 0)

10+ Year Member



how are you removing items?
i have a similar system like yours.
this is kind of a long way, but this is how i did it. and it works.

//first find the position in the array of the item you want to delete from cart

//second, make it null

//use a loop and assign the entire cart to a temp array skipping only the null values. i had a double array to store my items (item id, amount) so my loop is a litle different than the one i came up below.

$counter = 0;
for($i=0; $i<sizeof($cart); $i++){
if($cart[$i]!= null){
$temp[$counter] = $cart[$i];
}
}

//assign the temp array back to the cart session