PHP数组 - Json数据 - 生成表

时间:2015-11-27 18:03:19

标签: php html arrays json html-table

我正在尝试使用php数组生成一个包含数据的表。

这是我的php代码:

<?php       
            $result = array();
            ob_start();

            include 'include/podcastRead.php';

            $result = ob_get_clean();
 ?>

HTML表格:

    <table class="mdl-data-table mdl-js-data-table" id="tablee">
            <thead>
                <tr>
                    <th>ID</th>
                    <th class="mdl-data-table__cell--non-numeric">Nome</th>
                </tr>
            </thead>
            <tbody> 
                <tr>
                    <td>1</td>
                    <td class="mdl-data-table__cell--non-numeric">Nerdcast</td>
                </tr>
            </tbody>
    </table>

$ result数组有json数据,这里是:

{"podcast":[{"id":"1","nome":"Dan Carlin is Hardcore History"},{"id":"2","nome":"Dose Extra"}]}

我尝试了很多方法,在这里和其他网站上阅读和重读这么多帖子。 我不能创建一个表。

我也尝试了一些像DataTables这样的插件。

看起来很简单。洛尔。

我该怎么办?感谢。

1 个答案:

答案 0 :(得分:2)

如果您json_decode() $result您将获得一个对象,那么您就可以在$data->podcast上运行一个foreach循环并为每一行输出一个表。

<?php
$data = json_decode($result);
echo '<table class="mdl-data-table mdl-js-data-table" id="tablee">
    <thead>
        <tr>
            <th>ID</th>
            <th class="mdl-data-table__cell--non-numeric">Nome</th>
        </tr>
    </thead>
    <tbody>';
foreach ($data->podcast as $row) {
    echo '<tr>
        <td>'.$row->id.'</td>
        <td class="mdl-data-table__cell--non-numeric">'.$row->nome.'</td>
    </tr>';
}
echo '</tbody>
</table>';
?>