php - 从文本文件中获取数据并将其显示在html表格中

标签 php html file html-table

我为每一行都得到了一个这种模式的文本文件:

Username : Score

我正在尝试用它创建一个记分牌。

这是我的尝试:

<table width="200" border="1">
  <tr>
    <td width="85">Nom</td>
    <td width="99">Score</td>
  </tr>
  <tr>
    <td height="119"></td>
    <td></td>
  </tr>
</table>

问题是如何将每个 usernamescore 复制到表中(没有 : 字符)?

编辑:

我当前的 php 代码:

<?php 

    $file = file_get_contents('facile.txt', true);
    $arr = explode("/", $file, 2);
    $first = $arr[0];

?>

这只会给我第一个用户名,但我想从每一行中获取所有用户名。

最佳答案

这应该适合你:

在这里,我首先使用 file() 将所有行放入一个数组中其中每一行都是一个数组元素。在那里我忽略了每行末尾的空行和换行符。

在此之后,我用 array_map() 遍历每一行并使用 explode() 提取用户名 + 分数,然后我将其作为数组返回以创建多维数组,例如:

Array
(
    [0] => Array
        (
            [username] => a
            [score] => 5
        )
    //...

我使用 usort() 按得分对数组进行排序(要将 ASC 的顺序更改为 DESC,您只需将 > 中的 < 更改为 usort() 即可),之后我只需循环遍历数据并将其打印在表格中。

<?php 

    $lines = file("scores.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $data = array_map(function($v){
        list($username, $score) = explode(":", $v);
        return ["username" => $username, "score" => $score];
    }, $lines);

    usort($data, function($a, $b){
        if($a["score"] == $b["score"])
            return 0;
        return $a["score"] > $b["score"] ? 1 : -1;
    });

?>

<table width="200" border="1">
    <tr>
        <td width="85">Nom</td>
        <td width="99">Score</td>
    </tr>
<?php foreach($data as $user){ ?>
    <tr>
        <td height="119"><?php echo $user["username"]; ?></td>
        <td><?php echo $user["score"]; ?></td>
    </tr>
<?php } ?>
</table>

输出:

Nom   Score  // Nom   Score
 e      2    //  d     123
 a      5    //  c     26
 b     15    //  b     15
 c     26    //  a      5
 d    123    //  e      2

关于php - 从文本文件中获取数据并将其显示在html表格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29882108/

相关文章:

php - cakePHP通过关系绑定(bind)hasmany

javascript - 提前从 jquery 类型中获取值

html - 在包含同级图像的 div 中居中文本

java - 如何将多个对象写入文件?

linux - 从文件中剪切 13*10^6 行

java - 这两个java.io.File线程安全问题是否被规避了?

PHP:将 "’“字符从 ISO-8859-1 转换为 UTF-8 时出现问题

php - 在单行中上传多个图像,并使用逗号分隔路径

html - 搞乱格式化CSS

html - 将我的基本 <div> 样式设置为包含 “overflow:auto” 会有不利影响吗?