問題描述
我為每一行得到了一個這種模式的文本文件:
I got a text file in this pattern for each line:
Username : Score
我正在嘗試用它創(chuàng)建一個記分牌.
I'm trying to create a scoreboard out of this.
這是我的嘗試:
<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>
問題是如何將每個 username
和 score
復制到表中(沒有 :
字符)?
The question is how can I copy each username
and score
to the table (without the :
character) ?
我當前的 php 代碼:
My current php code:
<?php
$file = file_get_contents('facile.txt', true);
$arr = explode("/", $file, 2);
$first = $arr[0];
?>
這只會給我第一個用戶名,但我想獲取每一行的所有用戶名.
This will give me only the first username, but I want to get all the usernames from every line.
推薦答案
這應該適合你:
這里我首先使用 file()
其中每一行都是一個數(shù)組元素.在那里我忽略每行末尾的空行和換行符.
Here I first get all lines into an array with file()
where every line is one array element. There I ignore empty lines and new line characters at the end of each line.
在此之后,我使用 array_map()代碼>并使用
explode()提取用戶名+分數(shù)代碼>,然后我將其作為數(shù)組返回以創(chuàng)建一個多維數(shù)組,例如:
After this I go through each line with array_map()
and extract the username + score with explode()
, which I then return as array to create a multidimensional array, e.g:
Array
(
[0] => Array
(
[username] => a
[score] => 5
)
//...
我用 usort()
(要將順序從 ASC
更改為 DESC
,您只需將 >
更改為 <
> 在 usort()
) 之后,我簡單地遍歷數(shù)據(jù)并將其打印在表格中.
The I sort the array by the score with usort()
(To change the order from ASC
to DESC
you can just change >
to <
in usort()
) and after this I simply loop through the data and print it in the table.
<?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
這篇關于從文本文件中獲取數(shù)據(jù)并將其顯示在 html 表中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!