简体   繁体   中英

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. 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. Why is that?

It really depends on what the $records variable actually is. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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