How to output a value on every third result of a foreach statement in php?

前端 未结 11 1723
醉话见心
醉话见心 2021-01-04 13:37

I have a foreach statement in my app that echos a list of my database results:



        
相关标签:
11条回答
  • 2021-01-04 14:04
    <?php
    
    foreach ($featured_projects as $i => $fp) {
        echo '<div class="result' . ($i % 3 === 0 ? ' third' : '') . '">';
        echo $fp['project_name'];
        echo '</div>';
    }
    ?>
    
    0 讨论(0)
  • 2021-01-04 14:10

    add a counter in this loop and check if counter equals three and apply class.

    0 讨论(0)
  • 2021-01-04 14:14

    This is the working version, sorry for my prev version:

    <?php
    $featured_projects[0]['project_name'] = "pippo";
    $featured_projects[1]['project_name'] = "pippo2";
    $featured_projects[2]['project_name'] = "pippo3";
    
    $class[0] = "class1";
    $class[1] = "class2";
    
    $i=0;
    foreach($featured_projects as $fp) {
      $i++;
      if ($i == 3) {
        $c = $class[1];
        $i=0;
      } else {
        $c = $class[0];
      }
      echo "<div class=\"$c\">";
      echo $fp['project_name'];
      echo "</div>\n";
    }
    ?>
    

    Produces:

    <div class="class1">pippo</div>
    <div class="class1">pippo2</div>
    <div class="class2">pippo3</div>
    
    0 讨论(0)
  • 2021-01-04 14:16

    You can add a counter in loop ...try the following...

     <?php 
     $i = 0; 
     foreach($featured_projects as $fp) {
     $i = ++$i;
     if(($i%3) == 0)
     {
      $class1 = 'test1';
     }
     else
     {
     $class1 = 'test2';
     }
           echo '<div class="'.$class1.'">';
           echo $fp['project_name'];
           echo '</div>';
     }
     ?>
    
    0 讨论(0)
  • 2021-01-04 14:20

    Using a counter and modulo operator this is easy to implement

    0 讨论(0)
提交回复
热议问题