drkxgs9358 2013-06-06 14:54
浏览 28
已采纳

PHP无休止的循环

I have a piece of code which causes an endless loop but only in certain circumstances.

It's for a shopping cart quantity change and at the moment the cart works correctly when changing the quantity of the last item added. but for example if I have 3 items in the cart i can not change the quantity of the 1st or 2nd item because the loops runs endlessly.

Im not sure what is wrong with this code Ive found similar problems but no solution.

The code looks like this:

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
                if ($i > 50) die("manual termination");
} // close foreach loop

If i do a var_dump on the SESSION when i have added 2 items to the cart it displays the following:

array(2) { [0]=> array(2) { ["item_id"]=> string(11) "100-C09EJ01" ["quantity"]=> string(1) "3" } [1]=> array(2) { ["item_id"]=> string(11) "700-CF220EJ" ["quantity"]=> int(1) } }

Could someone help me please?

Thankyou in advance.

  • 写回答

1条回答 默认 最新

  • doushang8846 2013-06-06 15:02
    关注

    The problem is that you're modifying an array while you're looping over it. An extremely simple solution is to modify a copy of the array and then replace the original after the loop is finished.

    $newcart = $_SESSION["cart"];
    foreach ($_SESSION["cart"] as $each_item) { 
      $i++;
      while (list($key, $value) = each($each_item)) {
        if ($key == "item_id" && $value == $item_to_adjust) {
          array_splice($newcart, $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
        }
      }
      if ($i > 50) die("manual termination");
    }
    $_SESSION["cart"] = $newcart;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?