购物车阵列和会话

时间:2012-07-20 18:51:42

标签: php arrays session

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

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 

1 个答案:

答案 0 :(得分:0)

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

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

在这里,您要针对$ id key插入项目:

   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。

如果我在任何时候都不清楚,请询问,并告诉我是否还没有理解你的问题。

相关问题