【问题标题】:Multiple items in a PHP shopping cartPHP 购物车中的多个项目
【发布时间】:2010-05-22 21:43:29
【问题描述】:

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

提前致谢。

【问题讨论】:

    标签: php shopping-cart frequency


    【解决方案1】:

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

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

    $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;
    }
    

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

    【讨论】:

      【解决方案2】:

      内置的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)
      }
      

      【讨论】:

        【解决方案3】:

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

        例如:

        $_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');
        

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 2018-02-15
            • 1970-01-01
            • 2013-02-28
            • 2021-08-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-03-19
            相关资源
            最近更新 更多