使用PHP将JSON输出到HTML表

时间:2017-04-09 21:20:21

标签: php json

我使用bootstrap数据表来显示表中API的数据。这是数据:

{
  "response_status": {
    "status_code": 0,
    "status_message": [
      {
        "reg_number": "123",
        "company": "Company A",
        "office": "Orlando",
        "phone_number": "28122312345",
        "postal_address": "000",
        "postal_code": "000"
      },
      {
        "reg_number": "552",
        "company": "Company B",
        "office": "Miami",
        "phone_number": "28122312345",
        "postal_address": "000",
        "postal_code": "000"
      },
      {
       "reg_number": "154",
        "company": "Company C",
        "office": "San Francisco",
        "phone_number": "28122312345",
        "postal_address": "000",
        "postal_code": "000"
      }
    ]
  }
}

我需要输出html的结果:

<table>
<thead>
   <tr>
       <th>Reg No</th>
       <th>Company</th>
       <th>Office</th>
       <th>Phone Number</th>
       <th>Postal Address</th>
       <th>Postal Code</th>
   </tr>
</thead>

<tbody>
    <tr>
       <td>123</td>
       <td>Company A</td>
       <td>San Francisco</td>
       <td>28122312345</td>
       <td>000</td>
       <td>000</td>
   </tr>
   <tr>
       <td>552</td>
       <td>Company B</td>
       <td>Miami</td>
       <td>28122312345</td>
       <td>000</td>
       <td>000</td>
   </tr>
   <tr>
       <td>154</td>
       <td>Company C</td>
       <td>San Francisco</td>
       <td>28122312345</td>
       <td>000</td>
       <td>000</td>
   </tr>
</tbody>
<table>

有没有办法可以遍历JSON主体并使用php foreach循环自动为"status_message": [];之间的所有字段输出循环到我的表?

2 个答案:

答案 0 :(得分:0)

假设您的数据存储在$ data变量中,您的代码应如下所示:

<table>
<thead>
   <tr>
       <th>Reg No</th>
       <th>Company</th>
       <th>Office</th>
       <th>Phone Number</th>
       <th>Postal Address</th>
       <th>Postal Code</th>
   </tr>
</thead>
<tbody>
    <?php foreach($data->response_status->status_message as $message) : ?>
    <tr>
       <td><?php echo $message->reg_number; ?></td>
       <td><?php echo $message->company; ?></td>
       <td><?php echo $message->office; ?></td>
       <td><?php echo $message->phone_number; ?></td>
       <td><?php echo $message->postal_address; ?></td>
       <td><?php echo $message->postal_code; ?></td>
   </tr>
   <?php endforeach; ?>
</tbody>
<table>

答案 1 :(得分:0)

考虑到你的数据存储在一些变量中,比如$ your_data ... 使用json_decode($ your_data,true)以数组格式获取数据...然后循环数组