tags:

views:

52

answers:

2

If I have a table whose column count cannot be determined during the creation of the table, and whose rows may sometimes not contain enough data to fill each column, is there a way to have the last cell in each row auto-size?

I would prefer to not have to use colspan on the last cell in each row, because again, the max number of columns is not predictable when the table is being drawn.

For example:

-----------------------------------
NEW ROW | FOO | BAR                | <- last cell should span the length of the table
-----------------------------------
NEW ROW | FOO | BAR | TEST | BLAH  | <- no spanning needed, as it contains the most cols
-----------------------------------
NEW ROW | FOO | BAR | TEST         | <- last cell should span the length of the table
-----------------------------------
A: 

If you're dealing with DB records that might be blank or something, this pseudocode would get you started:

foreach ($query as $row) {
    $max_elements = 5; //per your example
    $number_of_elements = count($row);
    $colspan = $max_elements - $number_of_elements;
    $i = 0;
    while ($i <= $number_of_elements-2) {
        echo "<td>".$row['$i']."</td>";
        $i++;
    }
    echo "<td colspan='$colspan'>".$row['$number_of_elements-1']."</td>";
}

In this untested/unverified PHP, the premise is to count the number of items for each row, and know how many are left (based on a max number, like 5 in your example). Then echo out each item from the query, and for the last one add in the dynamically generated colspan #.

Debugging is left as an exercise to the reader.

Alex Mcp
+1  A: 

You could create a separate table for each row and use CSS to set the column widths to control layout. In this case the last cell would have its width set to "auto"

Alternatively if you know the maximum number of columns that you might have (or choose a number in excess of the number of columns that you will ever render), you can set the colspan on the last cell equal to that number minus the number of cells generated for that row.

For example, if you choose 100 as the maximum number of cells you will ever have, your above code would look like this...

<TABLE border="1">
   <TR><TD>NEW ROW</TD><TD>FOO</TD><TD COLSPAN="97">BAR</TD></TR>
   <TR><TD>NEW ROW</TD><TD>FOO</TD><TD>BAR</TD><TD>TEST</TD><TD COLSPAN="95">BLAH</TD></TR>
   <TR><TD>NEW ROW</TD><TD>FOO</TD><TD>BAR</TD><TD COLSPAN="96">TEST</TD></TR>
</TABLE>
pdavis