简体   繁体   中英

Shopping cart storing ID and quantity

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

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 .

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) {
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM