PHP 数组问题
我正在为朋友构建一个简单的购物车,并在会话中使用数组来存储它。
要将商品添加到购物车,我有以下代码
$next_item = sizeof($_SESSION['cart']) +1;
$_SESSION['cart'][$next_item] = array(item => $product_id, option => $option, qty => 1);
:如果有人添加另一个相同的商品或更新购物车,我正在努力解决如何更新此数组中的商品数量的问题。有人能指出我正确的方向吗?谢谢
I am building a simple cart for a friend and using an array in session to store it.
To add an item to the cart I have this code
$next_item = sizeof($_SESSION['cart']) +1;
$_SESSION['cart'][$next_item] = array(item => $product_id, option => $option, qty => 1);
What I'm struggling with how to update an item's quantity in this array should someone add another of the same item or update the cart. Can anyone point me in the right direction? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
就像
我会改变你的数组的结构。
而不是
Use
其中键是产品 id。这将使参考项目更容易,您可以在一行中更新数量
Something like
I would change the structure of your array.
Instead of
Use
Where the key is the product id. It will make referencing the items easier and you can update the quantity in one line
如果顺序不重要,您可以将产品存储在关联数组中。
If order is not important you can store your products in an associative array.
首先,您不需要计算数组大小:
其次,我将使用
$product_id
作为数组键。这样,搜索就很简单:First, you don't need to calculate the array size:
Second, I would use
$product_id
as array key. That ways, searches are straightforward:我不能说你为它选择了一个好的结构。如何在 $product_id 上建立索引呢?这样,您将始终知道您的购物车中是否已有特定商品:
I can't say that you've chosen a good structure for it. How about indexing upon the $product_id instead? That way, you'll always know if you already have a specific item in your cart:
要将商品添加到购物车,只需使用此命令(假设产品 ID 是唯一的):
要将任何给定产品 ID 的数量设置为 5,请使用此命令:
要将产品数量增加 3,请使用此命令:
To add something to the cart, simply use this (assuming product ids are unique):
To set the quantity for any given product id to 5, use this:
To increase the qty of a product by 3, use this: