Build HTML Tables Dynamically with PHP Part 2: Simplify with array_chunk()

Last week we built an HTML table on the fly using PHP. The process required a counter for monitoring which column was being displayed and some tests to determine when to add row tags. Let's look into simplifying the process with a built-in PHP function called array_chunk().

Background

As mentioned in the previous post, we'll be using HTML tables for design which isn't recommended. The task is better accomplished with CSS.

With that said, let's get back to coding tables. Here is the database information from last week (Build HTML Tables Dynamically with PHP Part 1) that we're displaying in rows of three:

id datePosted firstName lastName pictureName
1 2013-07-01 John Smith SmithJohn.jpg
2 2013-05-06 Elroy Johnson JohnsonElroy.jpg
3 2013-06-18 Jake Bible BibleJake.jpg
4 2013-07-17 Steve Stevenson StevensonSteve.jpg
5 2013-04-08 Bill Smith SmithBill2.jpg

Building HTML Tables

First, we'll initialize some variables to be used throughout the script. One indicates how many columns to display per row. The other holds the table output within an array.

<?php
//INITIALIZE VARIABLES
$colsToDisplay = 3;
$htmlOutput    = array();
?>

A MySQL query is then used to grab the database information shown earlier. Note that the loop only generates the code to display the columns. The tests to detect where the rows begin and end are unnecessary.

<?php
//INITIALIZE VARIABLES
$colsToDisplay = 3;
$htmlOutput    = array();
 
//GET PICTURE LIST
$sql = "SELECT datePosted, firstName, lastName, pictureName FROM pictureList ORDER BY datePosted DESC";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
     $htmlOutput[] = "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
}

?>

Once the loop is done, the array containing the column information can be broken into groups of three…or whatever value was assigned to $colsToDisplay.

<?php
while($row = $result->fetch_assoc()) {
     //...
}
 
//BREAK THE COLUMNS INTO GROUPS
$htmlOutput = array_chunk($htmlOutput, $colsToDisplay);

?>

All that's left is to display the table information. Note that array_chunk() creates a multi-dimensional array. The foreach loop is used to process the groups of columns. Each group is assigned to $currRow which contains an array of columns for the current row. The implode() function is used to quickly display the columns as a string.

<?php
//BREAK THE COLUMNS INTO GROUPS
$htmlOutput = array_chunk($htmlOutput, $colsToDisplay);
 
//DISPLAY TABLE
print '<table>';
foreach($htmlOutput as $currRow) {
     print '<tr>' . implode('', $currRow) . '</tr>';
}
print '</table>';

?>

Missing Column Tags

One thing you may have noticed is the code to add missing columns was left out. In other words, this example results in an HTML table where the last row only has two columns. The code from last week added the extra columns necessary so all rows had three columns.

Apparently, the missing columns aren't needed according to the W3C Markup Validation Service…so they weren't included. However, they can be added by running the following code right before array_chunk() is called:

<?php
//IF NEEDED, ADD MISSING COLUMNS
$colsDifference = count($htmlOutput) % $colsToDisplay;
if($colsDifference) {
     while($colsDifference < $colsToDisplay) {           $htmlOutput[] = '<td></td>';           $colsDifference++;      } } ?>

Final Code

Note that the following code is missing some essential tags (like <body>). You'll also need to establish a database connection.

<?php
//INITIALIZE VARIABLES
$colsToDisplay = 3;
$htmlOutput    = array();
 
//GET PICTURE LIST
$sql = "SELECT datePosted, firstName, lastName, pictureName FROM pictureList ORDER BY datePosted DESC";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
     $htmlOutput[] = "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
}
 
//============================== OPTIONAL CODE =================
//IF NEEDED, ADD MISSING COLUMNS
$colsDifference = count($htmlOutput) % $colsToDisplay;
if($colsDifference) {
     while($colsDifference < $colsToDisplay) {           $htmlOutput[] = '<td></td>';           $colsDifference++;      } } //========================= END: OPTIONAL CODE =================   //BREAK THE COLUMNS INTO GROUPS $htmlOutput = array_chunk($htmlOutput, $colsToDisplay);   //DISPLAY TABLE print '<table>'; foreach($htmlOutput as $currRow) {      print '<tr>' . implode('', $currRow) . '</tr>'; } print '</table>'; ?>

Conclusion

The final code is much easier to follow then what we had last week. Of course, it may take some time getting used functions like implode() and array_chunk().

Related Posts

0 Comments

There are currently no comments.

Leave a Comment