3.3. 将文件内容读入到数组中

未匹配的标注

持之以恒,方得始终!

前面的章节中,我们已经将订单写入文件中,我们这里再试下,将其读入到数组中,然后操作这个数组。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查看订单列表</title>
</head>
<body>
    <?php
    $document_root = $_SERVER['DOCUMENT_ROOT'];

    // 使用file(), 将整个文件载入数组中,每行为数组的一个元素
    $orders = file("$document_root/../orders/order.txt");

    $number_of_orders = count($orders);

    if($number_of_orders == 0) {
        echo "暂无订单";
        exit;
    }
    ?>

    <table border = 1>
        <tr>
            <th bgcolor = '#ccccff'>order date</th>
            <th bgcolor = '#ccccff'>tires</th>
            <th bgcolor = '#ccccff'>oil</th>
            <th bgcolor = '#ccccff'>spark plugs</th>
            <th bgcolor = '#ccccff'>total</th>
            <th bgcolor = '#ccccff'>address</th>
        </tr>

        <?php
        for($i=0; $i < $number_of_orders; $i++) {
            $line = explode(',', $orders[$i]);
            echo "<tr>
                <td>". $line[0] ."</td>
                <td>". intval($line[1]) ."</td>
                <td>". intval($line[2]) ."</td>
                <td>". intval($line[3]) ."</td>
                <td>". intval($line[4]) ."</td>
                <td>". $line[5] ."</td>
            </tr>";
        }
        ?>
    </table>
</body>
</html>

可以看到代码中,我们使用了explode()函数,来将一行文本中,根据,,再分割为数组。

如有任何侵权行为,请通知我删除,谢谢大家!
个人邮箱:865460609@qq.com

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
Junwind
讨论数量: 0
发起讨论 只看当前版本


暂无话题~