[英]How to create html table from multidimensional array in PHP?
我正在將HTTP請求發送到服務器,並獲得json格式的響應。 我將其轉換為數組:
$response = file_get_contents($final_url);
$responseArray = json_decode($response, true);
這是服務器響應數組( $responseArray
)。
Array (
[status] => OK
[result] => Array (
[0] => Array
(
[trainno] => 12151
[name] => SAMARSATA EXP
[cls] => 1A 2A 3A SL
[rundays] => F,Sa
[from] => BQA
[fromname] => Bankura
[dep] => 03.45
[to] => HWH
[toname] => Howrah Jn
[arr] => 08.25
[pantry] => 0
[type] => SUPERFAST
[datefrom] => 10-Apr-2015
[dateto] => 12-Apr-2020
[traveltime] => 04.40
)
[1] => Array
(
[trainno] => 12151
[name] => SAMARSATA EXP
[cls] => 1A 2A 3A SL
[rundays] => F,Sa
[from] => BQA
[fromname] => Bankura
[dep] => 03.45
[to] => HWH
[toname] => Howrah Jn
[arr] => 08.25
[pantry] => 0
[type] => SUPERFAST
[datefrom] => 10-Apr-2015
[dateto] => 12-Apr-2020
[traveltime] => 04.40
)
)
)
現在,如果[status] => OK,我想以html表格式打印'result'數組。 我該怎么辦?
只需添加一個if條件(如果滿足),則迭代所述數組,指向正確的索引:
if($responseArray['status'] === 'OK') {
foreach($responseArray['result'] as $result) {
echo $result['name']; // and other indices
}
}
將其打印到表標記中只是創建包含標記的普通表。
超級粗糙的例子:
<?php if($responseArray['status'] === 'OK'): ?>
<table>
<thead>
<tr>
<?php foreach($headers as $h): ?>
<th><?php echo $h; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach($responseArray['result'] as $row): ?>
<tr>
<?php foreach($row as $value); ?>
<td><?php echo $value; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.