2017-04-09 123 views
0

我使用引导数据表来显示表中API的数据。下面是数据:使用PHP将JSON输出到HTML表格

{ 
    "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体循环和自动输出环路的所有字段"status_message": [];使用PHP的foreach循环到我的表?

+1

可能的重复[如何从JSON使用PHP提取数据?](http://stackoverflow.com/questions/29308898/how-do -i-extract-data-from-json-with-php) –

回答

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> 
+0

这不起作用 – nick

+0

它应该工作!发生了什么错误? – MoeinPorkamel

+0

尝试获取为foreach()提供的非对象和无效参数的属性。你有没有尝试过自己的片段? – nick

0

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