【问题标题】:Cart arrays and sessions购物车数组和会话
【发布时间】:2012-07-20 18:51:41
【问题描述】:

好的,我遇到了这个问题。我正在尝试将产品添加到购物车作为选项颜色等,但我似乎无法正确处理。如果我只是点击“添加到购物车”,它会每次都会计数,但如果我改变颜色,它就会开始出错。帮助,男孩和女孩!已经为此工作了一段时间。

if(isset($_POST['submit'])){
                       $id = $_POST['id'];
                       $sleeve = $_POST['sleeve'];
                       $colour = $_POST['colour'];
                       $size = $_POST['size'];
                       $action = $_POST['action'];
                       $quantity = 1;
                       }
                       if(!isset($_SESSION['cart'][$id])){ 
                             $_SESSION['cart'][$id] = array($id, $colour, $size, $quantity);      
                       }
                          else{
                                if(isset($_SESSION['cart'][$id])){ // if the session as already been set then..
                                       while(list($key, $value) = each($_SESSION['cart'])){ // while loop to chech to content of the session..
                                              if($value[0] == $id && $value[1] == $colour && $value[2] == $size){ // checking to see if the session content is the same..
                                                    $quantity = $value[3] +=1;
                                                    $_SESSION['cart'][$id] = array($id, $colour, $size, $quantity); // if it is the same then add this..
                                                 }// if is ==
                                                    else{
                                                         $quantity +=1;
                                                         $_SESSION['cart'][$id][] = array($id, $colour, $size, $quantity); // is session is not the same do this..
                                                        }//else if it is not ==

                                             }// while
                                       }// if isset
                               }// else isset session 

【问题讨论】:

    标签: php arrays session


    【解决方案1】:

    似乎您正在检查购物车中的每个项目与一个项目,如果当前项目将在第一次迭代时匹配,那么它不应该退出循环并设置该项目存在的标志,因此在循环之后,增加该项目的数量,否则之后循环添加另一个实例。

    但是,当您下次添加产品的另一个实例并通过您的 if 部分进行检查时,您添加具有不同颜色的产品的其他实例的方式仍然无法正常工作。

    这里你要根据 $id 键插入项目:

       if(!isset($_SESSION['cart'][$id])){ 
                             $_SESSION['cart'][$id] = array($id, $colour, $size, $quantity);      
                       }
    

    在其他部分,当商品 ID 相同但属性不同时,您将产品添加到购物车的另一个​​子数组中:

    $_SESSION['cart'][$id][] = array($id, $colour, $size, $quantity); // is session is not the same do this..
    

    因此,您应该将每个产品/项目添加为:

    $_SESSION['cart'][$id][] = array($id, $colour, $size, $quantity); 
    

    在这两种情况下,要么是产品的第一个变体,要么是其他变体。

    但是,如果您的价格因变体而异,则为每个项目的每个变体使用不同的产品实例 ID。

    如果我有任何不清楚的地方,请询问,如果我还没有理解您的问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多