d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Php Session Shopping Cart > Removing Array Problem
Add Reply New Topic New Poll
Member
Posts: 5,269
Joined: Oct 18 2006
Gold: 21,400.00
May 14 2014 06:41pm
I am building a shopping cart for my website. I am having trouble removing items from the cart. Here are two lines of code:

Code
array_push($_SESSION['cart'], array($SKU,$quantity));
$_SESSION['cart'] = array_diff($_SESSION['cart'], array($SKU,$quantity));


In this test, an array of SKU/Quantity should be added, then removed in the next line. However the array is being added and NOT removed. What am I doing wrong in my remove line?
Member
Posts: 649
Joined: May 28 2012
Gold: 14.00
May 15 2014 03:22am
Quote (xandumx @ 15 May 2014 02:41)
I am building a shopping cart for my website.  I am having trouble removing items from the cart.  Here are two lines of code:

Code
array_push($_SESSION['cart'], array($SKU,$quantity));
$_SESSION['cart'] = array_diff($_SESSION['cart'], array($SKU,$quantity));


In this test, an array of SKU/Quantity should be added, then removed in the next line.  However the array is being added and NOT removed.  What am I doing wrong in my remove line?


what's your point ?
Member
Posts: 5,269
Joined: Oct 18 2006
Gold: 21,400.00
May 15 2014 12:47pm
Quote (FCNantes @ May 15 2014 02:22am)
what's your point ?


I am having trouble removing items from the cart. I only put these lines next to each other for an example. I want to be able to add an item to the cart(working). Then later be able to remove an item from the cart(not working).
Member
Posts: 5,269
Joined: Oct 18 2006
Gold: 21,400.00
May 21 2014 10:55am
Solution:

Code
function rem_from_array(&$session_array, $name)
{
foreach($session_array as $key=>$elem)
{
if($elem[0]==$name)
{
unset($session_array[$key]);
}
}
}

Code
rem_from_array($_SESSION['cart'],$SKU);


Answer derived from: http://stackoverflow.com/questions/14219290/remove-an-item-from-cart-session-multidimentional-array

:locked:
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll