1

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} 
}
2
  • Please post a sample JSON file to help us help you. Commented Dec 4, 2010 at 12:37
  • My JSON file:{ "John": { "status":"Wait" }, "Jennifer": { "status":"Active" }, "James": { "status":"Active", "age":56, "count":10, "progress":0.0029857, "bad":0 } } Commented Dec 4, 2010 at 12:42

1 Answer 1

5

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>"
Sign up to request clarification or add additional context in comments.

3 Comments

Thx, works great. Added ';' at the end of the 'echo "</thead></table>" '
Is it possible to sort the 'name' column. I tried several possibilities using sort(), but no luck so far.
That doesn't work. The name column isn't sorted. Also tried asort().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.