我目前正在尝试创建购物车。 当我仅将产品 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'];
}
我到处看了看,阅读了多维数组,但似乎没有什么适合我
最佳答案
我想我们可以安全地假设某个 ID 只需要存储一次,如果添加另一数量的相同产品,它可以与现有的合并。
因此,产品 ID 足以作为数组键,因为它是唯一的。
然后可以将数量存储为产品的值(value)。
您的购物车存储将显示为
$_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) {
// ...
}
关于php - 购物车存储 ID 和数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898185/