2017-04-09 120 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)以數組格式獲取數據...然後循環數組