简体   繁体   English

PHP foreach内部for循环仅运行一次

[英]PHP foreach inside for loop only runs once

I'm having a problem with a foreach loop inside a for loop only running the first time the for loop executes. 我在for循环内的foreach循环遇到问题,仅在第一次执行for循环时运行。 I need it to run every time. 我需要它每次都运行。

I have the following code: 我有以下代码:

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

    }

}

The output for this is: 输出为:

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"

As you can see, after the first run through the for loop, only the code above the foreach executes for the rest of the runs. 如您所见,在第一次运行for循环之后,对于其余的运行,只有foreach上方的代码才执行。 Why is that? 这是为什么?

It really depends on what the $records variable actually is. 这实际上取决于$ records变量的实际含义。 If its a database resource the first foreach reaches the end of that resultset, and the second run and so on there is nothing more to iterate over so doesn't execute. 如果它是数据库资源,则第一个foreach到达该结果集的末尾,然后第二次运行,依此类推,没有其他要迭代的内容,因此不会执行。

If you are using an older version of PHP you may need to reset the array pointer see http://php.net/manual/en/control-structures.foreach.php 如果您使用的是旧版PHP,则可能需要重置数组指针,请参见http://php.net/manual/zh/control-structures.foreach.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM