PHP 无限循环 呃


PHP Infinite Loop UGH

我有一个用于我正在构建的小型电子商务网站的购物车数组,并且遇到了一个我无法弄清楚的循环。如果我的购物车数组中有 3 种不同的产品(不确定产品数量是否超过 2 种)并且我尝试更新第二件商品的数量,它会导致无限循环并尝试连续添加产品再次作为新产品,而不是更新现有的相同产品。

    <?php 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//       Section 3 (if user chooses to adjust item quantity)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
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_array"] 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_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
                  } // close if condition
              } // close while loop
    } // close foreach loop
}
?>

我只是希望它更新现有产品的数量,而不是将其添加为另一个。提前感谢所有的帮助!

当您到达 array_splice 命令时,您可能正在重置数组指针,因此当 foreach 迭代下一项时,它实际上再次从第一项开始。

我建议你做的是,在array_splice之后设置一个标志,并打破while循环。 然后在下一次 foreach 迭代之前测试该标志,如果设置了,也突破该标志。

    array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
    $breakflag=true;
    break;
}
if($breakflag){
    break;
}