简体   繁体   English

更新购物车数量(部分有效)

[英]updating shopping cart quantity (partially works)

I have a shopping cart which at the moment allows me to add products, remove products and with 1 product in the cart I can change its quantity. 我有一个购物车,此刻我可以添加产品,删除产品,购物车中有1个产品,我可以更改其数量。

However if i have 2 products in the cart and I try to change the quantity of the first item the site crashes. 但是,如果我的购物车中有2件商品,而我尝试更改第一件商品的数量,则该网站将崩溃。 It doesnt reload the page with the new quantity it just times out and you can no longer click on any other links on the website. 它不会使用刚刚超时的新数量重新加载页面,您无法再单击网站上的任何其他链接。

The code to display the quantity is: 显示数量的代码是:

<form action="cart.php" method="post">
        <input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
        <input name="adjustBtn' . $pid . '" type="submit" value="Update" />
        <input name="item_to_adjust" type="hidden" value="' . $pid . '" />
</form>

and the code which deals with this is here: 与此相关的代码在这里:

if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
    // execute some code
    $item_to_adjust = $_POST['item_to_adjust'];
    $quantity = $_POST['quantity'];
    $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers
    if ($quantity >= 100) { $quantity = 99; }
    if ($quantity < 1) { $quantity = 1; }
    if ($quantity == "") { $quantity = 1; }
    $i = 0;
    foreach ($_SESSION["cart"] as $each_item) { 
              $i++;
              while (list($key, $value) = each($each_item)) {
                  if ($key == "item_id" && $value == $item_to_adjust) {
                      // That item is in cart already so let's adjust its quantity using array_splice()
                      array_splice($_SESSION["cart"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
                  } // close if condition
              } // close while loop
    } // close foreach loop
}
?>

been looking through answers on here but cant see a solution. 一直在这里寻找答案,但看不到解决方案。 Can anyone help me with this? 谁能帮我这个? I will try and provide any other information that may be needed to help. 我将尝试提供可能需要帮助的任何其他信息。

just to clarify, the cart works perfectly until I try to change the quantity of an item that isnt the last item I added. 只是为了澄清一下,购物车可以完美工作,直到我尝试更改不是我添加的最后一个商品的商品数量。 So if I have 3 items in the cart I cant change the quantity of item 1 or 2 but I can change item 3 因此,如果我的购物车中有3件物品,则无法更改物品1或2的数量,但可以更改物品3

Thanks in advance 提前致谢

The solution is to use a copy of the cart array for editing. 解决方案是使用购物车数组的副本进行编辑。

Editing the array which is currently being iterated can cause unexpected behaviour. 编辑当前正在迭代的数组可能会导致意外行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM