首页 > 解决方案 > HTML表格结构未按正确顺序显示数据

问题描述

我有一个显示来自 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>

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

标签: phphtmljsonforeachhtml-table

解决方案


尝试

<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>

推荐阅读