HTML表结构未按正确顺序显示数据

时间:2019-05-29 08:50:06

标签: php html json foreach html-table

我有一个表,用于显示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 个答案:

答案 0 :(得分: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>