跟踪购物车中产品的多个实例(具有不同选项)的最佳方法?
我正在开发一款轻型购物车,但对有多种选择的产品(例如多种尺寸的 T 恤)感到困惑。
数据库设计我没有问题。我有 shop_categories
和 shop_products
表,以及适用于 HABTM 关系的产品选项表。
我的问题是:如何在购物车中存储产品的多个实例(具有不同的选项)?
目前,我的购物车作为数组存储在 $_SESSION
中,包含产品详细信息并以产品 ID 为关键字。例如:
$cart = array(
32 => array(
'id' => 32,
'category' => 7,
'title' => 'Generic T-shirt',
'friendly_name' => 'generic-t-shirt',
'price' => '10.00',
'quantity' => 2
)
);
这工作得很好,但现在我被产品项目的介绍困住了。例如,如果有人将一件小 T 恤添加到购物车,然后将一件大 T 恤添加到购物车,我猜他们需要单独跟踪?
我怎样才能克服这个问题?我想我的第一个绊脚石是将购物车内容存储在产品 ID 上,但这就是我目前在有人添加或从购物车中删除时增加/减少数量的方式。例如:
if (isset($_POST['add_to_cart'])) {
// $_POST['product_id'] and $_POST['quantity'] are validated here
// to check they're both integers and the product actually exists
if (array_key_exists($cart[$product_id])) {
// increment quantity by $quantity
}
else {
// add product to cart and set to quantity to $quantity
}
}
抱歉,如果我胡言乱语,但我认为这应该充分概述我的应用程序和我面临的问题。我期待看到您的答案。
I'm developing a lightweight shopping cart but have become stumped with products that have options, e.g. a t-shirt in multiple sizes.
The database design I have no problem with. I have shop_categories
and shop_products
tables, and tables for product options that works with a HABTM relationship.
My problem is: how do I store multiple instances of a product (with different options) in my cart?
At the moment, my cart is stored as an array in the $_SESSION
, containing product details and keyed on the product's ID. For example:
$cart = array(
32 => array(
'id' => 32,
'category' => 7,
'title' => 'Generic T-shirt',
'friendly_name' => 'generic-t-shirt',
'price' => '10.00',
'quantity' => 2
)
);
This worked fine but now I'm stuck with the introduction for product items. For example, if someone adds a small t-shirt to the cart, and then a large t-shirt to the cart, they'll need to be tracked individually I'd surmise?
How can I overcome this? I guess my first stumbling block would be storing cart contents on the product ID, but this is how I currently increase/decrease quantity when someone adds or removes from their cart. For example:
if (isset($_POST['add_to_cart'])) {
// $_POST['product_id'] and $_POST['quantity'] are validated here
// to check they're both integers and the product actually exists
if (array_key_exists($cart[$product_id])) {
// increment quantity by $quantity
}
else {
// add product to cart and set to quantity to $quantity
}
}
Sorry if I'm rambled on but I think that should give a sufficient overview of my application and the problem I face. I look forward to seeing your answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我不重写你的整个代码,我建议将你的购物车重新格式化为这样的......
Without me rewriting your whole code, I suggest reformatting your cart to something like this...