I made an PHP OOP Cart Class like this
print_r($_SESSION["cart"]);
the result is:
Array ( [1] => 1 [3] => 2 )
How can I print this session, like a “real” cart?
example:
echo "Your basket: ";
echo "ItemID: ".$cartid." Itemnumber:".$cartnumber;
The adding to basket part:
if (isset($_POST['submit']))
{
$cart= new Cart();
$cart->add($_POST['id'],2);
$item= $cart->getCart();
$_SESSION["cart"]=$cart;
}
As an example, this code:
can be changed to:
Now, it’ll simply add to the array stored in $_SESSION[‘cart’]. Notice, that it doesn’t use the cart at all.
Try:
Edit: Some more explanation.
The cart class’ constructor accepts a parameter that it stores internally:
In all honestly, this should be a bit more intelligent:
This change guards against providing anything but an array to the constructor. Note, that it can still be given an array that the class doesn’t understand, e.g. a multidimensional array. In that situation, the cart class won’t destroy existing data in the array, unless an item id matches one of the keys in the original array.