well it's pretty easy to make a 2 column table with the modulus operator, but tonight i wanted to make a 3 column table.
the problem with creating dynamic tables is that if the number of rows of data you have is not equal to the exact number of columns, you will get tables that are not closed properly.
for example:
PHP Code:
<table>
<tr>
<td> data 1</td><td> data 2</td></tr>
<tr><td> data 3</td>
</tr>
</table>
u can fix that simply by using the modulus operator like this: ( i'll use an array for this example)
PHP Code:
<?
$i=0;
echo "<table>";
// start loop for each item in array
foreach($array as $each)
{
// if the remainder of $i divided by 2 == 0 then start a new row
if($i % 2 == 0)
{
echo "<tr>";
}
echo "<td>$each</td>";
// if it's on the last item of the array, add an extra <td></td> to complete the row
// only if it is on the first column of the table
if($i == ($count - 1))
{
if($i % 2 == 0)
{
echo "<td> </td>";
// increment $i so it knows to close the table
$i++;
}
}
// if the remainder of $i divided by 2 !=0 then end row
if($i % 2 != 0)
{
echo "</tr>";
}
}
echo "</table>";
?>
2 is easy to work with since every other number divided by 2 == 0.
But what do you do when you want 3 columns instead of 2? Well tonight I spent a lot of time working on this and I just thought I'd share.
PHP Code:
<?
$count=count($array);
$i=0;
echo "<table>";
foreach($array as $each)
{
// make a new if the remainder of $i divided by 3 == 0
if($i % 3 == 0)
{
echo "<tr>";
}
echo "<td width=125>$each</td>\n";
// add an extra <td></td> if there are not enough columns to complete the table
// only test if $i is on the last item of the array
if($i == ($count - 1))
{
// keep adding blank cells till it's at the end
while(($i + 1) % 3 != 0)
{
echo "<td> </td>\n";
$i++;
}
}
// end table row if the remainder of $i+1 divided by 3 is 0
if(($i + 1) % 3 == 0)
{
echo "</tr>";
}
$i++;
}
echo "</table>";
?>
let's say you wanted to make a 4, or 5 column table .. all you would have to do is replace the number "3" with however many columns you want, and this script should work.
maybe there is a better way to do this, but it is all i could come up with. fun fun =)