Store array of objects in PHP session
804
How can I store/remove/get an array of objects in the PHP session?
I tried this for adding:
array_push($_SESSION['cart'], serialize($item));
and this for removing:
function removeitem ($item)
{
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ )
{
if ($item.id == $arrayCart[i].id)
$arrayCart.splice (i,0);
}
}
But it doesn't work!!
Answer
Solution:
For Remove
It's Work For Me...
if this code Report Errors Please Comment to Check this...
Please check PHP version
Answer
Solution:
How has no one seen this:
Make it
{-code-2}
You also need another 2
}
to close yourif()
andfor()
statements so it's like this:Answer
Solution:
Have you tried using this?
You don't need to serialize the item-variable - a Session can store pure Objects, as long as the max. session-size doesn't exceed.
If you want to remove Items from the cart, you should use index-Names - this allows you to find your items faster.
I would probably use something like this:
In this case, the cart stores each item and its amount. Instead of
$itemName
, you could also use the item-ID from your database.To get an item from the cart, you will need this function:
Answer
Solution:
Try not pushing to array, because its probably not set yet, but to store to session, create new session var by:
to remove it:
EDIT:
Thanks to comments I realized that above code wouldn't store array in session. So, another short solution is to store to session var some JSON. Try this for a short test:
If that array is associative, you shoud use for decode: