Online Snippets Library

Create table from JSON In PHP

Here is simple example of how to make a table from a json.To convert json in to table we will use json_decode and foreach funtion.

<?php
$json ='[{"head":["Head1","Head2"], "rows":[["Row11", "Row12"],["Row21", "Row22"],["Row31", "Row32"]],"class": "myClass"}]';
$data = json_decode($json,true);

foreach ($data as $key => $jsons) {
 $table ='<table class="'.$jsons['class'].'" border="1">';
 foreach ($jsons as $rkey => $rvalue) {
    if($rkey=='head')
    {
        $table.='<tr>';
        foreach($rvalue as $rvv)
        {
            $table.='<th>'.$rvv.'</th>';
        }
        $table.='</tr>';
    }else
    if($rkey=='rows')
    {
        foreach($rvalue as $rvv)
        {
            $table.='<tr>';
            foreach($rvv as $rv)
            {
                $table.='<td>'.$rv.'</td>';
            }
            $table.='</tr>';
        }
    }
 }
}
echo $table;
?>