簡體   English   中英

如何將JSON數組轉換為HTML表

[英]How to convert JSON array to HTML table

我在PHP腳本中具有以下函數,該函數返回和API調用:

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以以下格式顯示原始數據:

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

我想在具有序列號,名字,姓氏列的HTML表中打印此數組

我猜數組索引是序列號,因此您可以執行以下操作:

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>';

並且,如果需要,不要忘記轉義HTML輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM