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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题