【问题标题】:PHP endless loopingPHP无限循环
【发布时间】:2013-06-02 15:44:31
【问题描述】:

我有一段代码会导致无限循环,但仅在某些情况下。

这是一个购物车数量的变化,当改变最后添加的物品的数量时,购物车可以正常工作。但例如,如果我在购物车中有 3 件商品,我无法更改第 1 件或第 2 件商品的数量,因为循环无休止地运行。

我不确定这段代码有什么问题我发现了类似的问题但没有解决方案。

代码如下:

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

如果我在将 2 件商品添加到购物车时在 SESSION 上执行 var_dump,它会显示以下内容:

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) } }

有人可以帮帮我吗?

提前谢谢你。

【问题讨论】:

  • $_SESSION["cart"] 中有什么内容?
  • 您能否在您的问题中添加$_SESSION 的var_dump?
  • 您在foreach($_SESSION["cart"]...) 中使用$_SESSION["cart"],然后在$_SESSION["cart"] array_splice($_SESSION["cart"]...) 中更改元素!!!不要这样做!!!
  • @andrewsi 好的,我已将其包含在问题中。 (furas)...感谢您的提醒,但我从在线教程中获得了此代码,我不知道任何替代方法

标签: php html session loops


【解决方案1】:

问题是您在循环遍历数组时正在修改它。一个极其简单的解决方案是修改数组的副本,然后在循环结束后替换原来的。

$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;

【讨论】:

  • 谢谢贾斯汀!!这已经解决了:-) 我已经坚持了几个小时......非常感谢
  • 这个$newcart = $_SESSION["cart"]; 创建一个副本
猜你喜欢
  • 2017-10-08
  • 2014-05-30
  • 1970-01-01
  • 2011-11-19
  • 2014-09-03
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
相关资源
最近更新 更多