[prog] php and formatting html tables

Mary mary-linuxchix at puzzling.org
Mon Aug 8 08:50:37 EST 2005


On Sun, Aug 07, 2005, Wolf Rising wrote:
> is it possible to modify the loop so it would print separate tables? I
> tried adding an if statement if($row['Blg'] ==1) but that didn't work
> out very well and it would get kinda messy. 

It would also not be very flexible... what happens when $row['Blg'] == 4
or $row['Blg'] == 1000000. In programming you should try and solve the
general problem...

My PHP isn't so good, so here's the solution I'd use in a kind of
pseudo-code mixed with PHP, comments begin with #

# store the current Blg value
currentBlg = Nothing
print '<table>'
while $row == mysql_fetch_row {

    # capture the very first $row['Blg'] value, so that we can end
    # the first table when the time comes.
    if $currentBlg is equal to Nothing {
        $currentBlg = currentBlg = $row['Blg']
    }

    # if this $row['Blg'] value is not the same as the last row, then
    # it's time for a new table
    if $row['Blg'] does not equal currentBlg {
        # end the current table and start a new one
        print '</table>'
        print '<table>'
        # store the new currentBlg so that we can end this table
        # at the right time
        currentBlg = $row['Blg']
    }

    print the $row value
}
# end the final table
print '</table>'

This makes several assumptions: the biggest is that the results are
sorted by their Blg value. If they aren't, for example if they come out
as 1, 2, 1, 1, 2, 3, 2, 1, then you will get a table every time it
changes value.

This particular idiom of storing the current value of something and then
taking a particular action when it changes is a very common technique. A
similar one is used to find the maximum value of a list, for example:

1. set the current maximum to the first value in the list
2. for each item in the list, if the item is bigger than the current
   maximum, make it the new current maximum
3. the current maximum is now set to the biggest item in the list

-Mary


More information about the Programming mailing list