php - 购物车存储 ID 和数量

标签 php mysql

我目前正在尝试创建购物车。 当我仅将产品 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/

相关文章:

mysql - 从表中选择数据时出现问题?

Python 与 MySql "SAWarning: Unicode type received non-unicode bind param value"错误

php - Magento _ $weee Helper->type Of Display() 方法

javascript - 在 Javascript 音乐播放器播放列表中使用 PHP

php - Mysql通过函数INSERTing数据

php - 使用 PHP 和 MySQL 将多个值与数据库中的多个列进行比较?

php - jQuery如何将类添加到具有特定类名的第三级子div的父div

php - 使用 php 处理来自 iphone 应用程序的 json base64 编码图像

mysql - 'localhost.localdomain' 中的未知列 'field list'

java - 包含不在日期范围内的月份的 MySQL 计数