php - Shopping cart storing ID and quantity -


i trying create shopping cart. works when store array product id, need store quantity too.

i have function

public static function addtocart($data) {  if(!isset($_session['cart'])) {   $_session['cart'] = array();  }   else {   array_push($_session['cart'], $data['id']);  } } 

i have function items cart

public static function getcart() {  if(count($_session['cart'])>0) {    $ids = "";    foreach($_session['cart'] $id) {    $ids = $ids . $id . ",";   }     $ids = rtrim($ids, ',');    $q = dibi::fetchall("select * eshop_products idproduct in ({$ids})");   return $q;  } else {   } } 

then assign function variable , use foreach.

$cart = cart::getcart();  foreach($cart $c) {  echo $c['price']; } 

i looked everywhere, read multidimensional arrays, nothing seems work me

i guess can safely assume id nees stored once, , if quantity of same product added, can merge existing.

hence, product id sufficient array key, unique.
quantity can stored value product.

your cart storage appear as

$_session['cart'] = array(     123 => 3 // product 123 quantity 3     254 => 1 // product 254 quantity 1 ); 

to add cart, 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 cart items later, can use extended form of foreach:

foreach($_session['cart'] $id => $quantity) {     // ... } 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -