Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting json data to an HTML table

I have an array of data in php and I need to display this data in a HTML table. Here is what an example data set looks like.

Array(
  Array
  (
     [comparisonFeatureId] => 1182
     [comparisonFeatureType] => Category
     [comparisonValues] => Array
                 (
                 [0] => Not Available
                 [1] => Standard
                 [2] => Not Available
                 [3] => Not Available
                 )
    [featureDescription] => Rear Seat Heat Ducts
),)

The dataset is a comparison of 3 items (shown in the comparisonValues index of the array)

In the end I need the row to look similar to this

<tr class="alt2 section_1"> 
   <td><strong>$record['featureDescription']</strong></td> 
   <td>$record['comparisonValues'][0]</td> 
   <td>$record['comparisonValues'][1]</td> 
   <td>$record['comparisonValues'][2]</td> 
   <td>$record['comparisonValues'][3]</td> 
</tr>   

The problem I am coming across is how to best do this. Should I create the entire table HTML on the server side pass it over an ajax call and just dump pre-rendered HTML data into a div or pass the json data and render the table client side.

Any elegant suggestions?

like image 586
dnaluz Avatar asked Jul 03 '26 12:07

dnaluz


2 Answers

That depends. There are several factors to be taken into account:

  1. How much CPU and network bandwidth do you want to waste on the webserver? Generating and sending HTML eats more than just sending a compact JSON string.

  2. How much CPU and memory do you want to waste on the webbrowser? Generating a table in HTML DOM tree eats more than just inserting a ready-generated string as innerHTML.

  3. How reuseable do you want the webservice to be? Returning "static" HTML isn't useful for everyone. A more flexible format like XML or JSON is more useful (also for yourself in the future).

As far, I'd suggest returning JSON and have JS/jQuery to populate it on the client side.


Update: assuming that the JSON data will arrive in this format

var json = {"features": [{
    "comparisonFeatureId": 1182,
    "comparisonFeatureType": "Category",
    "comparisonValues": [ "Not Available", "Standard", "Not Available", "Not Available" ],
    "featureDescription": "Rear Seat Heat Ducts"
}, {
    "comparisonFeatureId": 1183,
    "comparisonFeatureType": "Category",
    "comparisonValues": [ "Not Available", "Standard", "Not Available", "Not Available" ],
    "featureDescription": "Some Description"
}]};

and that you have an empty table like this

<table id="table"></table>

then you can use the following jQuery script to fill it the way you described in the question

$.each(json.features, function(i, feature) {
    var row = $('<tr class="alt2 section_1">').appendTo($('#table'));
    row.append($('<td>').append($('<strong>').text(feature.featureDescription)));
    $.each(feature.comparisonValues, function(j, comparisonValue) {
        row.append($('<td>').text(comparisonValue));
    });
});
like image 190
BalusC Avatar answered Jul 06 '26 03:07

BalusC


dnaluz,

as mentioned by others, there are great libs out there to do thios client side. I'd also take the stance that you'd be best sending the json array to the client and then using the lib to present the data in tabular format.

Altho i mention the use of nice presentation libs to create the table, below is a little function that i use for lightweight quick and dirty table visualizations from a json array:

function CreateTableFromJson(objArray) {
    // has passed in array has already been deserialized
    var array = typeof  objArray != 'object' ? JSON.parse(objArray) : objArray;

    str = '<table class="tableNormal">';
    str += '<tr>';
    for (var index in array[0]) {
        str += '<th scope="col">' + index + '</th>';
    }
    str += '</tr>';
    str += '<tbody>';
    for (var i = 0; i < array.length; i++) {
        str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
        for (var index in array[i]) {
            str += '<td>' + array[i][index] + '</td>';
        }
        str += '</tr>';
    }
    str += '</tbody>'
    str += '</table>';
    return str;
}

hope this is useful in some minor way.. jim

[edit] - here's a link to a page using a very similar technique: http://www.zachhunter.com/2010/04/json-objects-to-html-table/

like image 34
jim tollan Avatar answered Jul 06 '26 02:07

jim tollan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!