TPSstar
TPSstar

Reputation: 881

Generating table for database records

The following code will generate <tr></tr> on every $product->title

<table>
    <?php foreach ($products as $product) {
            echo '<tr>
                      <td>'.$product->title.'</td>
                  </tr>';
    }?>
</table>

But I want to generate the row after every three columns as output of above code.

<table>
    <tr>
            <td>$product->title/td>
            <td>$product->title/td>
            <td>$product->title</td>
    </tr>
            <td>$product->title</td>
            <td>$product->title</td>
            <td>$product->title</td>
    </tr>
</table>

Upvotes: 0

Views: 310

Answers (3)

vyshak
vyshak

Reputation: 41

    $i=1;
    <table>
        <?php foreach ($products as $product) {
           if ( $i<= 3 ) {
               if($i==1) {
                 echo '<tr>';
               }    
               echo '<td>'.$product->title.'</td>';
               $i++;
           }
           else {
               echo'</tr>';
               $i=1;
           }
        }?>
    </table>

Upvotes: 0

Cyclonecode
Cyclonecode

Reputation: 29991

Perhaps something like this:

<table>
<?php
   $count = count($products); 
   foreach ($products as $key => $product) {
        // print on first row and third row
        if($key % 3 == 0) {
            echo '<tr>';
        }
        echo '<td>'.$product->title.'</td>';
        // print on third row or on last element
        if((($key + 1) % 3 == 0 && $key > 0) || $key == $count-1) {
            echo '</tr>';
        }
   }
?>
</table>

If you array isn't indexed from 0 and up you would have to use a counter for the $key variable.

Upvotes: 0

dar7yl
dar7yl

Reputation: 3747

I use this form so much, that it's committed to type memory.

<table>
<?php
    $count = 0;  // we gotta count them lines
    foreach ($products as $product)
    {
        if ( ($count % 3) == 0 )  // every 3 lines
        {
            if ($count > 0)  // not at first line
                echo '</tr>';  // close previous row
            echo '<tr>';  // open new row
         }
         ++$count;  // better count this one now.

         echo '<td>'.$product->title.'</td>;
    }
    if ($count > 0) 
        echo '</tr>';  // close last row
?>
</table>

Upvotes: 1

Related Questions