• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to display the query results in a random html table?

#1
[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,

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

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

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

Best Regards,

#4
[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.

#5
[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.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.