CodeIgniter Forums
How to display the query results in a random html table? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: How to display the query results in a random html table? (/thread-23536.html)



How to display the query results in a random html table? - El Forum - 10-14-2009

[eluser]Sinclair[/eluser]
Hi,

I need to display the query results in a view to an random HTML table.

The HTML table need to display 4 columns, like this:

1 2 3 4
5 6 7 8
9 10

How can I easly do this?

Best Regards,


How to display the query results in a random html table? - El Forum - 10-14-2009

[eluser]richfearless[/eluser]
I suggest you use the modulus operator, here is an example..

Code:
if ($count % 3){
print '</tr><tr>';
}



How to display the query results in a random html table? - El Forum - 10-14-2009

[eluser]Sinclair[/eluser]
Hi, thaks for your reply but I don't get how to do that. Can you give an example?

Best Regards,


How to display the query results in a random html table? - El Forum - 10-14-2009

[eluser]BrianDHall[/eluser]
I would do a foreach loop and increase a variable each time at the end of the loop. Before the loop you echo out a <tr>. At the start of the loop you check to see if the variable has reached your max table width in rows, and if so you output a </tr><tr> beforeing continuing with the print of your TDs.

Something like:

Code:
echo '<tr>';
$i = 0;

foreach ($results as $r)
{
if ($i >= 4)
{
echo '</tr><tr>';
$i = 0;
}
echo "<td>$r</td>";

$i++
}

echo '</tr>';

EDITED to fix what jedd pointed out.


How to display the query results in a random html table? - El Forum - 10-14-2009

[eluser]jedd[/eluser]
Note that both richfearless's and BrianDHall's approaches require a ++ in there somewhere - a $count++ and a $i++ respectively.

Code:
// As an example, pilfering Brian's demonstration code

$i = 0;

echo '<tr>';
foreach ($results as $r)  {
    if ($i > 3)  {
        echo '</tr><tr>';
        $i = 0;
        }

    echo "<td>$r</td>";

    $i++;
    }

echo '</tr>';

Note also - using a modulus approach means you wouldn't have to reset the $i=0 within your test on each iteration, which would reduce your code count by one line, but would be arguably be less obvious for those not familiar with that pattern .. take your pick.


EDIT: Oh, btw, what does 'random' mean in your context? I feel we may possibly have missed your intent here.