[英]Shopping cart storing ID and quantity
我目前正在尝试创建购物车。 当我仅将产品 ID 存储到数组中时它有效,但我也需要存储数量。
我有一个功能
public static function addToCart($data) {
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
else {
array_push($_SESSION['cart'], $data['id']);
}
}
我还有一个功能可以从购物车中获取商品
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 {
}
}
然后我将函数分配给变量并使用 foreach。
$cart = Cart::getCart();
foreach($cart as $c) {
echo $c['price'];
}
我到处寻找,阅读多维数组,但似乎对我没有任何作用
您可以使用$_SESSION['cart']
作为 key->value 数组,其中 key 是productID
,value 是quantity
:
$_SESSION['cart'] = array(5 => 1, 6 => 2);
要获取键数组,请使用array_keys
。 要在查询中使用ids
,请使用implode
。
我想我们可以安全地假设某个 ID 只需要存储一次,如果添加另一个数量的相同产品,它可以与现有的合并。
因此,产品 ID 足以作为数组key ,因为它是唯一的。
然后可以将数量存储为产品的价值。
然后您的购物车存储将显示为
$_SESSION['cart'] = array(
123 => 3 // Product 123 with quantity 3
254 => 1 // Product 254 with quantity 1
);
要添加到购物车,这将起作用:
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;
}
}
要稍后检索购物车项目,您可以使用foreach
的扩展形式:
foreach($_SESSION['cart'] as $id => $quantity) {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.