John Doe
John Doe

Reputation: 10203

php create dynamic html table

I need to create a dynamic html table using PHP after parsing a JSON file.
I need this column structure for my table; Name | Status | Age | Count | Progress | Bad

How can I create a new row for every 'record' parsed from the JSON file (I can create a tab separated string).
An additional difficulty is that some 'records' only contain data for the column 'Name' and others for all columns.

So my question is how to add a row dynamically to the table and fill the right column ?
(The key form the JSON file is the column header)

Example of JSON format:

{ 
"John":     {"status":"Wait" }, 
"Jennifer": {"status":"Active" }, 
"James":    {"status":"Active","age":56,"count":10,"progress":0.0029857,"bad":0} 
}

Upvotes: 1

Views: 9500

Answers (1)

01001111
01001111

Reputation: 836

Something like this would work:

$data = json_decode($json_string);
$columns = array();

echo "<table><tbody>";
foreach ($data as $name => $values) {
    echo "<tr><td>$name</td>";
    foreach ($values as $k => $v) {
        echo "<td>$v</td>";
        $columns[$k] = $k;
    }
    echo "</tr>";
}
echo "</tbody><thead><tr><th>name</th>";
foreach ($columns as $column) {
    echo "<th>$column</th>";
}
echo "</thead></table>"

Upvotes: 5

Related Questions