Most languages provide plenty of array utility functions from slicing(), merging, flattening(), filtering() and mapping(), but one thing that you typically have to do yourself is transform arrays to display them in a tabular format. Why would you want to do this? Presenting information in a table is a great way to separate categories, sort elements, as well as maximize screen real estate. I recently arranged an array of objects into a 4 x 3 table of checkboxes in order to avoid having a list of up to 15 items, which would necessitate a lot of scrolling on the user’s part. In today’s article, I’ll show you how to dynamically transform the contents of a one-dimension array into an HTML table on both the server and client, using PHP and JavaScript respectively.
The Array Structure
For the purposes of today’s examples, the display function expects an array of objects where each has two properties: a slug (unique key) and name (label):
Element 1: {slug: ‘menu_allergen_milk’, name: ‘Milk’}
Element 2: {slug: ‘menu_allergen_peanut’, name: ‘Peanuts’}
Element 3: {slug: ‘menu_allergen_sulphites’, name: ‘Sulphur dioxide’}
Element 4: {slug: ‘menu_allergen_celery’, name: ‘Celery’}
Element 5: {slug: ‘menu_allergen_seafood’, name: ‘Seafood’}
Element 6: {slug: ‘menu_allergen_mustard’, name: ‘Mustard’}
etc…
Advertisement
Producing an HTML Table using PHP
Whatever language you employ to implement the functionality, the idea is always the same:
Print out the start of the table, up to, but not including the first <TR> row tag.
Iterate over each array element. For each element:
If it’s the first cell, print the <TR> row tag.
Print the table cell and element contents.
If we’ve printed the number of columns that we want, print the closing <TR> row tag and reset the cell counter.
Accomplishing the same thing in JavaScript requires surprisingly few syntax changes. In the following client-side code, the selected allergens are displayed within a table in a read-only format – i.e., without the checkboxes. Another change is that empty cells are added to complete the last row if necessary. It just looks better with borders.
I prefer to place the script at the bottom of the page and invoke printArrayInTabularFormat() as an inline function. You can even pass arguments to it by including them in the closing parentheses!
var$menu_tags = [
{slug: 'menu_allergen_milk', name: 'Milk'},
{slug: 'menu_allergen_peanut', name: 'Peanuts'},
{slug: 'menu_allergen_sulphites', name: 'Sulphur dioxide'},
{slug: 'menu_allergen_celery', name: 'Celery'},
{slug: 'menu_allergen_seafood', name: 'Seafood'},
{slug: 'menu_allergen_mustard', name: 'Mustard'}
];
var MENU_TAGS_COLUMN_COUNT = 4;
(functionprintArrayInTabularFormat(menuTags, colCount) {
var html = '<table name="tblMenuAllergens" cellpadding="1" border="1"><thead></thead><tbody>' + "n";
var cellIndex=1;
for (var$i=0; $i<menuTags.length; $i++) {
if (cellIndex == 1) {
html += '<tr>';
}
var$id = menuTags[$i]['slug'];
var$name = menuTags[$i]['name'];
html += '<td width="120">' + $name + '</td>' + "n";
if (++cellIndex > colCount) { //close the row
html += '</tr>';
cellIndex = 1;
}
}
//finish empty cellsvar remainingCellsCount = menuTags.length % colCount;
if (remainingCellsCount) {
for (var$i=0; $i<remainingCellsCount; $i++) {
html += '<td width="120"> </td>' + "n";
}
html += '</tr>';
}
html += '</tbody></table>' + "n";
html += '</td></tr></tbody></table>' + "n";
document.getElementById('allergensTable').innerHTML = html;
})($menu_tags, MENU_TAGS_COLUMN_COUNT);
For best results I would remove all of the table, row, and cell attributes and move them to a CSS file. That would help make the function as generic as possible.
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.
The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.
Advertiser Disclosure: Some of the products that appear on
this site are from companies from which TechnologyAdvice
receives compensation. This compensation may impact how and
where products appear on this site including, for example,
the order in which they appear. TechnologyAdvice does not
include all companies or all types of products available in
the marketplace.