【问题标题】:PHP foreach inside for loop only runs oncePHP foreach 在 for 循环中只运行一次
【发布时间】:2015-11-22 00:05:27
【问题描述】:

我在 for 循环内的 foreach 循环仅在 for 循环第一次执行时运行时遇到问题。我每次都需要它运行。

我有以下代码:

for ($numberId = 0; $numberId <= count($items[0])-1; $numberId++) {

    echo 'numberId is '.$numberId;
    var_dump($items[0][$numberId]);

    foreach ($records as $bottle) {

       echo 'bottle array is:'; 
       var_dump($bottle);

    }

}

这个的输出是:

numberId is 0
string(19) "some bottle"
bottle array is:array(6) {
  ["market_name"]=>
  string(47) "another bottle"
  [0]=>
  string(47) "another bottle"
  ["avg_price_7_days"]=>
  string(6) "137.99"
  [1]=>
  string(6) "137.99"
  ["current_price"]=>
  string(6) "134.06"
  [2]=>
  string(6) "134.06"
}
bottle array is:array(6) {
  ["market_name"]=>
  string(50) "some other bottle"
  [0]=>
  string(50) "some other bottle"
  ["avg_price_7_days"]=>
  string(4) "2.95"
  [1]=>
  string(4) "2.95"
  ["current_price"]=>
  string(4) "2.92"
  [2]=>
  string(4) "2.92"
}
bottle array is:array(6) {
  ["market_name"]=>
  string(33) "a third bottle"
  [0]=>
  string(33) "a third bottle"
  ["avg_price_7_days"]=>
  string(4) "1.25"
  [1]=>
  string(4) "1.25"
  ["current_price"]=>
  string(4) "1.22"
  [2]=>
  string(4) "1.22"
}
numberId is 1string(27) "a new bottle"
numberId is 2string(32) "some really old bottle"
numberId is 3string(47) "another bottle"
numberId is 4string(28) "some other bottle"
numberId is 5string(29) "a third bottle"

如您所见,在第一次运行 for 循环之后,只有 foreach 上面的代码在其余的运行中执行。这是为什么呢?

【问题讨论】:

  • 你有没有把涉及的变量转储出去?输出很好,但对解决问题没有意义。转储$items 和$records 怎么样

标签: php loops for-loop foreach


【解决方案1】:

这实际上取决于 $records 变量实际上是什么。如果它是数据库资源,则第一次 foreach 到达该结果集的末尾,并且第二次运行等等,则没有更多可迭代的内容,因此不会执行。

如果您使用的是旧版本的 PHP,您可能需要重置数组指针,请参阅 http://php.net/manual/en/control-structures.foreach.php

【讨论】:

  • 啊,就是这样! $records 是一个数据库资源。我不知道 foreach 不能再经历一次。我现在先将它保存在一个数组中,然后一切正常。谢谢!!!!
猜你喜欢
  • 1970-01-01
  • 2014-12-07
  • 2013-11-28
  • 2014-12-29
  • 1970-01-01
  • 2021-06-15
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多