使用result中的变量创建循环表

时间:2014-05-15 06:41:19

标签: php loops html-table

我从网站API中提取了一些信息,并存储在$result中。我想创建一个包含此信息的表,循环x次(常量)。以下是我目前如何手动重复它的工作原理。我想象一下,必须有一个更好/更简单的方法,然后每次手动重复它。

<tr>
    <td><?php echo strtoupper($result['weapons']['0']['stat']['id']); ?></td>
    <td><?php echo round($result['weapons']['0']['extra']['accuracy'],2); ?>%</td>
    <td><?php echo round($result['weapons']['0']['extra']['kpm'],2); ?></td>
    <td><?php echo number_format($result['weapons']['0']['stat']['shots']); ?></td>
    <td><?php echo number_format($result['weapons']['0']['stat']['hits']); ?></td>
    <td><?php echo number_format($result['weapons']['0']['stat']['kills']); ?></td>
    <td><?php echo number_format($result['weapons']['0']['stat']['hs']); ?></td>
    <td><?php echo round($result['weapons']['0']['extra']['hkp'],2); ?>%</td>
</tr>
<tr>
    <td><?php echo strtoupper($result['weapons']['1']['stat']['id']); ?></td>
    <td><?php echo round($result['weapons']['1']['extra']['accuracy'],2); ?>%</td>
    <td><?php echo round($result['weapons']['1']['extra']['kpm'],2); ?></td>
    <td><?php echo number_format($result['weapons']['1']['stat']['shots']); ?></td>
    <td><?php echo number_format($result['weapons']['1']['stat']['hits']); ?></td>
    <td><?php echo number_format($result['weapons']['1']['stat']['kills']); ?></td>
    <td><?php echo number_format($result['weapons']['1']['stat']['hs']); ?></td>
    <td><?php echo round($result['weapons']['1']['extra']['hkp'],2); ?>%</td>
</tr>

我无法绕过如何循环这个问题?我搜索并查看过很多文章,我似乎无法开始工作。

2 个答案:

答案 0 :(得分:3)

如果您想要查看每个结果,最简单的方法就是使用foreach

e.g。

foreach($result['weapons'] as $tr){ ?>
<tr>
    <td><?= strtoupper($tr['stat']['id']) ?></td>
    <td><?= round($tr['extra']['accuracy'],2) ?>%</td>
    //... etc.
</tr>
<?php } //...

如果您更喜欢定义循环数量,请使用&#34;对于&#34;

for ($i = 0; $i <= 10; $i++) { ?>
<tr>
    <td><?= strtoupper($result['weapons'][$i]['stat']['id']) ?></td>
    <td><?= round($result['weapons'][$i]['extra']['accuracy'],2) ?>%</td>
    <td><?= round($result['weapons'][$i]['extra']['kpm'],2) ?></td>
    //.... etc.
</tr>
<?php }

答案 1 :(得分:0)

它非常容易使用foreach循环让我们假设你在变量$ result_api中获得了你的值然后遍历这个数组 $ I = 0;

foreach($result_api as $result)
{ ?>
<tr>
    <td><?php echo strtoupper($result['weapons'][$i]['stat']['id']); ?></td>
    <td><?php echo round($result['weapons'][$i]['extra']['accuracy'],2); ?>%</td>
    <td><?php echo round($result['weapons'][$i]['extra']['kpm'],2); ?></td>
    <td><?php echo number_format($result['weapons'][$i]['stat']['shots']); ?></td>
    <td><?php echo number_format($result['weapons'][$i]['stat']['hits']); ?></td>
    <td><?php echo number_format($result['weapons']['0']['stat']['kills']); ?></td>
    <td><?php echo number_format($result['weapons'][$i]['stat']['hs']); ?></td>
    <td><?php echo round($result['weapons'][$i]['extra']['hkp'],2); ?>%</td>
</tr>
<?php 
$i++;

}