【问题标题】:Outputing JSON to an HTML table using PHP使用 PHP 将 JSON 输出到 HTML 表
【发布时间】:2017-04-09 21:20:21
【问题描述】:

我使用引导数据表在表中显示来自 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": []; 之间的所有字段的循环自动输出到我的表?

【问题讨论】:

标签: php json


【解决方案1】:

假设你的数据存储在 $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>

【讨论】:

  • 试图获取为 foreach() 提供的非对象和无效参数的属性。你自己试过sn-p吗?
  • @nick 是的,它的作品。也许您没有将数据存储在 $data 变量中,或者您的 $data 变量是数组!告诉我们您如何从 api 获取数据并将其发送到您的视图。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多