Search code examples
phpsimplepie

dynamic rows and columns inside a foreach loop


I'm trying, but I'm stucked with the logic... so, I have this:

$max_items=10;

echo '<table>';
echo '<tr>';

foreach ($feed->get_items(0, $max_items) as $item): 

echo '<td>';
echo $some_value; 
echo '</td>';

endforeach; 

echo '</tr>';
echo '</table>';

I want to show the results like this:

[1][2]
[3][4]
[5][6]
[7][8]
[9][10]

I have to use a while statement? A for loop? Inside or outside the foreach code?

I really don't get it...

Thanks for any kind of help


Solution

  • Here's a very simple example of how to do this sort of HTML building.

    <?php
    
    $data = range( 'a', 'z' );
    $numCols = 2;
    
    echo "<table>\n";
    echo "\t<tr>\n";
    
    foreach( $data as $i => $item )
    {
        if ( $i != 0 && $i++ % $numCols == 0 )
        {
            echo "\t</tr>\n\t<tr>\n";
        }
        echo "\t\t<td>$item</td>\n";
    }
    
    echo "\t</tr>\n";
    echo '</table>';
    

    This way, you can change $numCols to be 3 or 4 (or any number) and always see that number of columns in the output, and it does so without using an nested loop.