2

我正在用 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>';

提前致谢。

4

4 回答 4

6

为什么不构建更强大的购物车实现?

考虑从这样的数据结构开始:

$cart = array(
  'lines'=>array(
     array('product_id'=>14,'qty'=>2),
     array('product_id'=>25,'qty'=>1)
   )
);

或类似的。

然后您可以创建一组对购物车结构进行操作的函数:

function addToCart($cart, $product_id, $qty){
   foreach($cart['lines'] as $line){
     if ($line['product_id'] === $product_id){
       $line['qty']  += $qty;
       return;
     }
   }
   $cart['lines'][] = array('product_id'=>product_id, 'qty'=>$qty);
   return;
}

当然,您可以(也许应该)更进一步,将这个数据结构和函数组合成一组类。购物车是以面向对象的方式开始细化的好地方。

于 2010-05-22T22:01:38.260 回答
1

内置的array_count_values函数可能会完成这项工作。

例如:

<?php
$items = array(14,14,14,11,10);
var_dump(array_count_values($items));
?>

输出:

array(3) {
  [14]=>
  int(3)
  [11]=>
  int(1)
  [10]=>
  int(1)
}
于 2010-05-22T22:26:16.223 回答
1

您将受益于使用多维数组以更健壮的结构存储数据。

例如:

$_SESSION['cart'] = array(
  'lines'=>array(
     array('product_id'=>14,'quantity'=>2, 'item_name'=>'Denim Jeans'),
     ...
   )
);

然后要将新商品添加到购物车中,您只需执行以下操作:

$_SESSION['cart'][] = array('product_id'=45,'quantity'=>1, 'item_name'=>'Jumper');
于 2011-10-16T22:46:09.550 回答
0

当您让用户添加项目时,您需要将其添加到数组中的正确位置。如果产品 id 已经存在于数组中,则需要更新它。还要始终小心尝试输入零或负数的用户!

于 2012-11-23T12:48:27.043 回答