Reputation: 325
I am currently trying to create shopping cart. It works when I store into array only product ID, but I need to store quantity too.
I have a function
public static function addToCart($data) {
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
else {
array_push($_SESSION['cart'], $data['id']);
}
}
I also have a function to get items from cart
public static function getCart() {
if(count($_SESSION['cart'])>0) {
$ids = "";
foreach($_SESSION['cart'] as $id) {
$ids = $ids . $id . ",";
}
$ids = rtrim($ids, ',');
$q = dibi::fetchAll("SELECT * FROM eshop_products WHERE idProduct IN ({$ids})");
return $q;
} else {
}
}
Then I assign function to variable and use foreach.
$cart = Cart::getCart();
foreach($cart as $c) {
echo $c['price'];
}
I looked everywhere, read about multidimensional arrays, but nothing seems to work for me
Upvotes: 0
Views: 2068
Reputation: 1479
I guess we can safely assume that a certain ID only nees to be stored once, and if another quantity of the same product is added, it can merge with the already existing.
Hence, the product ID is sufficient as array key, as it is unique.
The quantity can then be stored as value for the product.
Your cart storage would then appear as
$_SESSION['cart'] = array(
123 => 3 // Product 123 with quantity 3
254 => 1 // Product 254 with quantity 1
);
To add to the cart, this would work:
public static function addToCart($item, $quantity) {
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if(isset($_SESSION['cart'][$item])) {
$_SESSION['cart'][$item] += $quantity;
} else {
$_SESSION['cart'][$item] = $quantity;
}
}
To retrieve the cart items later, you can use the extended form of foreach
:
foreach($_SESSION['cart'] as $id => $quantity) {
// ...
}
Upvotes: 2
Reputation: 54841
You can use $_SESSION['cart']
as key->value array where key is productID
and value is a quantity
:
$_SESSION['cart'] = array(5 => 1, 6 => 2);
For getting array of keys use array_keys
. For using ids
in a query use implode
.
Upvotes: 2