PHP表问题

时间:2015-09-14 13:05:43

标签: php html-table

我在下面有以下代码。该表直接显示在彼此之下,与正常方式相邻。我希望表格显示为普通表格,但使用以下语法,每列都会显示在另一列之下。

表格应如下所示:

Sky 1         |   Sky 2        |   Sky 3
sky1result        sky2result       sky3result
sky1result        sky2result       sky3result


<?php

        $f = fopen("/home/app/sky1result.txt", "r");
        echo "<table>";
        echo "<tr><th>Sky 1</th></tr>";
        while(!feof($f)) {
            echo "<tr><td>";
            echo fgets($f),"</td></tr>";
        }

        fclose($f);

        $f1 = fopen("/home/app/sky2result.txt", "r");
        echo "<tr><th>Sky 2</th></tr>";
        while(!feof($f1)) {
            echo "<tr><td>";
            echo fgets($f1),"</td></tr>";
        }

        fclose($f1);

        $f2 = fopen("/home/app/sky3result.txt", "r");
        echo "<tr><th>Sky 3</th></tr>";
        while(!feof($f2)) {
            echo "<tr><td>";
            echo fgets($f2),"</td></tr>";
        }

        fclose($f2);
        echo "</table>";
     ?>

1 个答案:

答案 0 :(得分:1)

修改 好的,这有点棘手。这是您发表评论后的更新版本。

<?php

        // Lets start with collecting the data.
        $column1 = [];
        $f = fopen("/home/app/sky1result.txt", "r");
        while(!feof($f)) {
            $column1[] = fgets($f);
        }
        fclose($f);

        $column2 = [];
        $f = fopen("/home/app/sky2result.txt", "r");
        while(!feof($f)) {
            $column2[] = fgets($f);
        }
        fclose($f);

        $column3 = [];
        $f = fopen("/home/app/sky3result.txt", "r");
        while(!feof($f)) {
            $column3[] = fgets($f);
        }
        fclose($f);

        // We now have three arrays.
        // Lets figure out wich is the largest, so we know how many rows we need.
        $maxRows = max(count($column1), count($column2), count($column3));

     ?>

<table>
    <tr>
        <!-- The headers -->
        <th>Sky 1</th><th>Sky 2</th><th>Sky 3</th>
    </tr>
    <?php for ($i=0; $i < $maxRows; $i++): ?>
        <tr>
            <!-- this is a row. In it we print the column on that row if it exists -->
            <td><?php echo isset($column1[$i]) ? $column1[$i] : '' ?></td>
            <td><?php echo isset($column2[$i]) ? $column2[$i] : '' ?></td>
            <td><?php echo isset($column3[$i]) ? $column3[$i] : '' ?></td>
        </tr>
    <?php endfor ?>
</table>