PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 4.27 Program: Printing an Array in a Horizontally Columned HTML Table

Converting 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( )
function pc_grid_horizontal($array, $size) {

    // compute <td> width %ages
    $table_width = 100;
    $width = intval($table_width / $size);

    // define how our <tr> and <td> tags appear
    // sprintf() requires us to use %% to get literal %
    $tr = '<tr align="center">';
    $td = "<td width=\"$width%%\">%s</td>";

    // open table
    $grid = "<table width=\"$table_width%\">$tr";

    // loop through entries and display in rows of size $sized
    // $i keeps track of when we need a new table tow
    $i = 0;
    foreach ($array as $e) {
        $grid .= sprintf($td, $e);
        $i++;

        // end of a row
        // close it up and open a new one
        if (!($i % $size)) {
            $grid .= "</tr>$tr";
        }
    }

    // pad out remaining cells with blanks
    while ($i % $size) {
        $grid .= sprintf($td, '&nbsp;');
        $i++;
    }

    // add </tr>, if necessary
    $end_tr_len = strlen($tr) * -1;
    if (substr($grid, $end_tr_len) != $tr) {
        $grid .= '</tr>';
    } else {
        $grid = substr($grid, 0, $end_tr_len);
    }

    // close table
    $grid .= '</table>';

    return $grid;
}

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:

// establish connection to database
$dsn = 'mysql://user:password@localhost/table';
$dbh = DB::connect($dsn);
if (DB::isError($dbh)) { die ($dbh->getMessage( )); }

// query the database for the 50 states
$sql = "SELECT state FROM states";
$sth = $dbh->query($sql);

// load data into array from database
while ($row = $sth->fetchRow(DB_FETCHMODE_ASSOC)) {
  $states[ ] = $row['state'];
}

// generate the HTML table
$grid = pc_grid_horizontal($states, 6);

// and print it out
print $grid;

When rendered in a browser, it looks like Figure 4-1.

Figure 4-1. The United States of America
figs/phpc_0401.gif

Because 50 doesn't divide evenly by six, there are four extra padding cells in the last row.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    4.1 Introduction
    Recipe 4.2 Specifying an Array Not Beginning at Element 0
    Recipe 4.3 Storing Multiple Elements per Key in an Array
    Recipe 4.4 Initializing an Array to a Range of Integers
    Recipe 4.5 Iterating Through an Array
    Recipe 4.6 Deleting Elements from an Array
    Recipe 4.7 Changing Array Size
    Recipe 4.8 Appending One Array to Another
    Recipe 4.9 Turning an Array into a String
    Recipe 4.10 Printing an Array with Commas
    Recipe 4.11 Checking if a Key Is in an Array
    Recipe 4.12 Checking if an Element Is in an Array
    Recipe 4.13 Finding the Position of an Element in an Array
    Recipe 4.14 Finding Elements That Pass a Certain Test
    Recipe 4.15 Finding the Largest or Smallest Valued Element in an Array
    Recipe 4.16 Reversing an Array
    Recipe 4.17 Sorting an Array
    Recipe 4.18 Sorting an Array by a Computable Field
    Recipe 4.19 Sorting Multiple Arrays
    Recipe 4.20 Sorting an Array Using a Method Instead of a Function
    Recipe 4.21 Randomizing an Array
    Recipe 4.22 Shuffling a Deck of Cards
    Recipe 4.23 Removing Duplicate Elements from an Array
    Recipe 4.24 Finding the Union, Intersection, or Difference of Two Arrays
    Recipe 4.25 Finding All Element Combinations of an Array
    Recipe 4.26 Finding All Permutations of an Array
    Recipe 4.27 Program: Printing an Array in a Horizontally Columned HTML Table
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele