简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM