我在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上面的代码执行其余的运行。那是为什么?
答案 0 :(得分:2)
这实际上取决于$ records变量实际上是什么。如果它是一个数据库资源,第一个foreach到达结果集的末尾,第二个运行等等,没有什么可以迭代,所以不执行。
如果您使用的是旧版本的PHP,则可能需要重置数组指针,请参阅http://php.net/manual/en/control-structures.foreach.php