PHP 购物车中的多个商品
我正在用 PHP 制作购物车。为了检查用户是否选择了多个产品,我将所有内容放入一个数组中($contents)。当我输出它时,我得到类似“14,14,14,11,10”的内容。我想要“3 x 14、1 x 11、1 x 10”之类的东西。最简单的方法是什么?我真的不知道该怎么做。
这是我的代码中最重要的部分。
$_SESSION["cart"] = $cart;
if ( $cart ) {
$items = explode(',', $cart);
$contents = array();
$i = 0;
foreach ( $items as $item ) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
$i++;
}
$smarty->assign("amount",$i);
echo '<pre>';
print_r($contents);
echo '</pre>';
提前致谢。
I'm in the progress of making a shopping cart in PHP. To check if a user has selected multiple products, I put everything in an array ($contents). When I output it, I get something like "14,14,14,11,10". I'd like to have something like "3 x 14, 1 x 11, 1 x 10". What is the easiest way to do that? I really have no clue how to do it.
This is the most important part of my code.
$_SESSION["cart"] = $cart;
if ( $cart ) {
$items = explode(',', $cart);
$contents = array();
$i = 0;
foreach ( $items as $item ) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
$i++;
}
$smarty->assign("amount",$i);
echo '<pre>';
print_r($contents);
echo '</pre>';
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不构建一个更强大的购物车实施?
考虑从这样的数据结构开始:
或类似的。
然后,您可以创建一组对购物车结构进行操作的函数:
当然,您可以(也许应该)更进一步,将此数据结构和函数组合到一组类中。购物车是开始以面向对象的方式思考的好地方。
Why not build a more robust cart implementation?
Consider starting with a data-structure like this:
Or similar.
Then you could create a set of functions that operate on the cart structure:
Of course, you could (and perhaps should) go further and combine this data structure and functions into a set of classes. Shopping carts are a great place to start thining in an object-oriented way.
内置的 array_count_values 函数可能可以完成这项工作。
例如:
输出:
The built-in array_count_values function might does the job.
E.g:
Outputs:
使用多维数组以更稳健的结构存储数据将使您受益匪浅。
例如:
然后要将新商品添加到购物车,您可以简单地执行以下操作:
You would benefit from using a multi dimensional array to store your data in a more robust structure.
For example:
Then to add new items to the cart you can simply do this:
当您让用户添加项目时,您需要将其添加到数组中的正确位置。如果数组中已经存在产品 id,则需要更新它。还要始终小心尝试输入零或负数的用户!
When you let a user add an item you need to add it in the right position in the array. If the product id already exist in the array, you need to update it. Also always be careful of users trying to enter zero or minus numbers!