简体   繁体   中英

Change a while loop to foreach?

I'm about to change a code to "WordPress-customized code" (using $wpdb). And with $wpdb->get_results() I get an array that need to be outputted with a foreach loop. But the problem is that my current while-loop has a "$initial_hidden statement" in it that I don't know how to do with the new foreach.

Here is my current code:

while (($initial_hidden == true) || ($r = mysql_fetch_assoc($q))) {

...

}

So, how do I get the "initial hidden" to this:

foreach ($q as $r) {

...

}

So, how do I get the "initial hidden" to this

You can abort foreach with regular break; so simply add if() in loop body and break when condition is met.

foreach($q as $r) {
     ...

   if ($initial_hidden) {
      break;
   }
}

Please use this line of code: $r = mysql_fetch_assoc($q); if(($initial_hidden) || (mysql_num_rows($q) > 0)) { foreach($r as $key => $value) { //result } }

You can also have foreach inside the while loop

while (($initial_hidden == true) || !empty(mysql_fetch_assoc($q))) {
foreach($r = mysql_fetch_assoc($q)){
}
...

} 

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