0

您好,我正在使用下面的代码检查具有相同 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();
    }
    ?>
4

2 回答 2

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();
}
于 2013-06-22T08:31:04.430 回答
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;
              } 
           } 
于 2013-06-22T08:47:56.913 回答