简体   繁体   中英

PHP for loop inside a while loop

I'm fairly new to PHP and to get a better understanding of it I'm building a small application where I can add movies into watchlists, see upcoming movies, ...

Right now I'm trying to build a top rated list that lists all the movies a user has added in order from highest to lowest rating.

The syntax I have right now is:

<?php
          while($avr = mysql_fetch_array($rating)) {
            for ($i=1; $i<5; $i++){ ?>
            <li class="movie"><?php echo $i . ' - ' . $avr['title'] . '<div class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li>
<?php } } ?>

"$i<5;" in the for-loop is hardcoded at the moment for testing, this will be replaced with a variable.

The problem I have with this is that it counts from 1 to 4 for each "$avr['title']". So it prints each movie title 4 times on my page. I just want the first movie title to be "1", the second "2", etc.

If I place the for-loop outside the while-loop, each movie will be "1".

So my question is, how can I integrate a for-loop within a while-loop that counts up just once for each while-loop value?

Thanks in advance.

You don't need a for loop. You just need a counter variable (I named it $i here) you increment each time you enter the while loop:

$i = 0;
while($avr = mysql_fetch_array($rating)) {
?>
    <li class="movie"><?php echo ++$i . ' - ' . $avr['title'] . '<div class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li>
<?php
    // Increment & Insert ---------^
}

You don't need the for loop.

<?php
      $i=1;
      while($avr = mysql_fetch_array($rating)) {            
        <li class="movie"><?php echo $i . ' - ' . $avr['title'] . '<div    class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li>
<?php  $i++;
  } ?>
<?php
$i = 1;
          while($avr = mysql_fetch_array($rating)) {
              if($i < 5) {
?>
              <li class="movie"><?php echo $i . ' - ' . $avr['title'] . '<div class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li>
<?php          $i++; } } ?>

Also you can add else clause to break the loop after your desired iterations

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