How to convert JSON array to HTML table

I have the following function in a PHP script, which returns and API call:

if (in_array((int)$result['code'], array(200, 201))) {
    $presult=(json_decode($result['body'],true));
    print_r($presult);
 } else {
    print("error parsing result");
    var_dump($result);
 }

$presult displays raw data in the following format:

Array
(
    [contacts] => Array
        (
            [users] => Array
                (
                    [0] => Array
                        (
                            [first_name] => Peter
                            [last_name] => Parker

I want to print this array in an HTML table with columns serial no., First name, Last

Answers


I guess the array index is the serial number, so you can do this:

echo '<table>
<tr>
   <th>Serial Number</th>
   <th>First name</th>
   <th>Last name</th>
</tr>';

foreach($presult['contacts']['users'] as $number => $user){
   echo '<tr>
            <td>' . $number . '</td>
            <td>' . $user['first_name'] . '</td>
            <td>' . $user['last_name'] . '</td>
         </tr>';
}

echo '</table>';

And don't forget to escape the HTML output if required.


Need Your Help

fixed position div freezes on page (iPad)

ipad ios5 css-position

I have an asp.net web site I am building to be supported on ipad. When I focus on an input element and the keyboard pops up, the position fixed header div(which normally scrolls along with the page)