【问题标题】:HTML Table structure not displaying data in right orderHTML表格结构未按正确顺序显示数据
【发布时间】:2019-10-14 19:55:15
【问题描述】:

我有一个显示来自 JSON 的数据的表。我能够在表格中显示数据,但它不能很好地呈现表格。

表格的结构被扭曲了。它不会按照我希望它显示的顺序显示数据。

<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
            <th>Amount</th>
        </tr>
    </thead>

    <?php 
        $url = 'xxxxxxxxxxxxxxxxxxxxxx'; // path to your JSON file
        //$url = 'data.json'; // path to your JSON file
        $data = file_get_contents($url); // put the contents of the file into a variable
        $characters = json_decode($data);
        $i = 0;
    ?>
    <tbody>
        <tr>
        <?php
            foreach ($characters as $character) 
            {
                ?>   
            <td>
                <?php echo $character->name; ?>
            </td>
            <td>
                <?php echo $character->phoneNumber; ?>
            </td>
            <td>
                <?php echo $character->amount; ?>
            </td>
            <?php }
        ?>
        </tr>
    </tbody>
</table>

我希望只有三列。数据以正确的顺序显示

【问题讨论】:

  • 很难说不知道 1:JSON 是什么样子,2:tabletable-bordered 类的 CSS 是什么样子,3:您是否使用 jQuery datatables插件(猜测是因为 id 是 dataTable) - 任何这些都可能破坏布局

标签: php html json foreach html-table


【解决方案1】:

试试

<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
    <tr>
        <th>Name</th>
        <th>Number</th>
        <th>Amount</th>
    </tr>
</thead>

<?php 
            $url = 'xxxxxxxxxxxxxxxxxxxxxx'; // path to your JSON file
            //$url = 'data.json'; // path to your JSON file
            $data = file_get_contents($url); // put the contents of the file into a variable
            $characters = json_decode($data);
            $i = 0;
            ?>
    <tbody>
        <?php
            foreach ($characters as $character) 
            {
             ?>
            <tr>
                <td>
                    <?php echo $character->name; ?>
                </td>
                <td>
                    <?php echo $character->phoneNumber; ?>
                </td>
                <td>
                    <?php echo $character->amount; ?>
                </td>
            </tr>
            <?php }
            ?>
    </tbody>
</table>

【讨论】:

  • 他们为什么要试试这个?是什么让你改变了,为什么?
  • @Dharman,对不起我的英语不好。我认为他们将 放在 foreach 循环之外,当 foreach 运行时,只会在一个 ... 上创建超过 3 个
  • 你应该尽可能地解释你的答案。不需要太多,但至少用一句话来说明您建议的更改。不要告诉人们尝试某事。听起来你下达了命令。教他们犯了什么错误。
  • 我很想这么做,但是我的英语还不够。对不起!
  • @shandonjoe 我很高兴!
猜你喜欢
相关资源
最近更新 更多
热门标签