4.27. Program: Printing an Array in a Horizontally Columned HTML TableConverting an array into a horizontally columned table places a fixed number of elements in a row. The first set goes in the opening table row, the second set goes in the next row, and so forth. Finally, you reach the final row, where you might need to optionally pad the row with empty table data cells. The function pc_grid_horizontal( ) , shown in Example 4-8, lets you specify an array and number of columns. It assumes your table width is 100%, but you can alter the $table_width variable to change this. Example 4-8. pc_grid_horizontal( )
The function begins by calculating the width of each <td> as a percentage of the total table size. Depending on the number of columns and the overall size, the sum of the <td> widths might not equal the <table> width, but this shouldn't effect the displayed HTML in a noticeable fashion. Next, define the <td> and <tr> tags, using printf-style formatting notation. To get the literal % needed for the <td> width percentage, use a double %%. The meat of the function is the foreach loop through the array in which we append each <td> to the $grid. If you reach the end of a row, which happens when the total number of elements processed is a multiple of number of elements in a row, you close and then reopen the <tr>. Once you finish adding all the elements, you need to pad the final row with blank or empty <td> elements. Put a nonbreaking space inside the data cell instead of leaving it empty to make the table renders properly in the browser. Now, make sure there isn't an extra <tr> at the end of grid, which occurs when the number of elements is an exact multiple of the width (in other words, if you didn't need to add padding cells). Finally, you can close the table. For example, let's print the names of the 50 U.S. states in a six-column table:
When rendered in a browser, it looks like Figure 4-1. ![]() Figure 4-1. The United States of AmericaBecause 50 doesn't divide evenly by six, there are four extra padding cells in the last row.
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|