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
Post a Comment