我有一个脚本可以从文本文件中收集数据并将其显示在 HTML 表格中。这是非常简单的编码。但我想要做的是让表格显示按 .$parts[1].
列排序的结果。正如现在的脚本一样,它显示按 .$parts[0].
列排序的结果。
我试图让它与 usort
一起工作,但我已经放弃了。
这是我的代码:
<table class="heavyTable">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Length</th>
</tr>
</thead>
<tbody>
<?php
$file_handle = fopen("bardate_domains.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(' ', $line_of_text);
$tmp = explode('.', $parts[0]);
echo "<tr><td>".$parts[0]."</td><td>".$parts[1]."</td><td>".strlen($tmp[0])."</td></tr>";
}
fclose($file_handle);
?>
</tbody>
</table>
我很感激我能得到的任何帮助:)
编辑: 文本文件如下所示:
0086.se 2017-04-02
0102design.se 2017-03-03
0141.se 2017-04-21
0158.se 2017-03-27
016fotboll.se 2017-03-31
020716.se 2017-04-12
021webb.se 2017-04-23
总共有大约 40.000 行。
最佳答案
<?php
$fileHandler = fopen("bardate_domains.txt", "rb");
$data = [];
while (!feof($fileHandler) ) {
// read file row
$row = fgets($fileHandler);
$index = count($data);
// explode array by space
$data[$index] = explode(' ', $row);
// explode data[$index][0] by '.', then insert into array in index 0 & 1
array_splice($data[$index], 0, 1, explode('.', $data[$index][0]));
}
// sort array by array index 1
usort($data, function ($prev, $next) {
if ($prev[1] == $next[1]) {
return 0;
}
return ($prev[1] < $next[1]) ? -1 : 1;
});
fclose($fileHandler);
?>
<table class="heavyTable">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Length</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $item): ?>
<tr>
<td><?= $item[0] . '.' . $item[1] ?></td>
<td><?= $item[2] ?></td>
<td><?= $item[1] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
关于php - 对 HTML 表格中的文本文件中的数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42266782/