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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)