未能调整项目金额

时间:2013-06-22 08:18:53

标签: php pdo

您好我正在使用下面的代码检查具有相同pid,长度和类别的商品是否已经在购物篮中,如果是,则应调整商品的数量。问题是,如果添加具有相同pid,长度和类别的项目,而不是数量增加。它作为新产品添加到购物篮中。

NOTE: An item has the same pid but it comes in different sizes and category.

    if (isset($_POST['pid'])) {
        $pid = $_POST['pid'];
        $length = $_POST["size"];
        $qty = $_POST['Qty'];
        $Category = $_POST['Category'];

        $wasFound = false;
        $i = 0;
        if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { 
            $_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $qty));
        } else {
            foreach ($_SESSION["cart_array"] as $each_item) { 
                  $i++;
                  while (list($key, $value, $ilength, $pcategory) = each($each_item)) {
                      if ($key == "item_id"  && $ilength == $length && $pcategory == $Category && $value == $pid) {

                          array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $each_item['quantity'] + 1)));
                          $wasFound = true;
                      } 
                  } 
               } 
               if ($wasFound == false) {
                   array_push($_SESSION["cart_array"], array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $qty));
               }
        }
        header("location: cart.php"); 
        exit();
    }
    ?>

2 个答案:

答案 0 :(得分:0)

试试这个......

if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $qty));
    } else {
        foreach ($_SESSION["cart_array"] as $key=>$each_item) { 

            if(($each_item['item_id']==$pid && ($each_item['length']==$length)&&($each_item['Category']==$Category)){
                  $_SESSION["cart_array"][$key]['quantity']++;
                  $wasFound = true;
                      $wasFound = true;
                }
            }  

           if ($wasFound == false) {
               array_splice($_SESSION["cart_array"], array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $qty));
           }
    }
    header("location: cart.php"); 
    exit();
}

答案 1 :(得分:0)

我会尝试一下;) 更新和测试代码

foreach ($_SESSION["cart_array"] as $array_key=>$each_item) { 
              if ($each_item['item_id'] == $pid  && $each_item['length'] == $length && $each_item['Category'] == $Category) {
                      $_SESSION["cart_array"][$array_key]['quantity']+=$qty;
                      $wasFound = true;
              } 
           }