购物车阵列和会话


Cart arrays and sessions

好吧,我有问题。我正试图将产品添加到购物车中,作为选项颜色等等,但我似乎做不对。如果我只是点击"添加到购物车",它每次都会计数,但如果我改变颜色,它就会开始出错。救命,伙计们,女孩们!我已经为此工作了一段时间。

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 

看起来你正在对照一个项目检查购物车中的每一个项目,如果当前项目在第一次迭代时匹配,那么它不应该退出循环并设置项目存在的标志,这样在循环之后,增加项目数量,否则在循环之后添加另一个实例。

但是,当你下次添加另一个产品实例并通过你的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。

如果我在任何时候都不清楚,那么请问,如果我还没有理解你的问题,也请告诉我。