我使用 PHP 访问文本文件中包含的一些数据。
以下是文本文件 (myfile.txt) 的示例 - 每行都有三个字段,由 || 分隔:
4e84||some text||category A f17b||words words||category B f7ac||some more text here||category B 8683||text text||category C b010||more text||category A fcc4||more text||category B we47||more text||category C 08ml||more text||category A
这是我用来在简单的 HTML 表格中显示 txt 文件内容的 PHP 代码。 我访问该文件并循环遍历每一行以提取三个部分:
<?php
$lines = file("myfile.txt");
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>TEXT</th>
<th>CATEGORY</th>
</tr>
</thead>
<tbody>
<?php
foreach ($lines as $line) {
list($id,$text,$category) = explode('||', $line);
echo '<tr>';
echo '<td>'.$id.'</td>';
echo '<td>'.$text.'</td>';
echo '<td>'.$category.'</td>';
echo '</tr>';
}
?>
</tbody>
</table>
我需要根据第三个字段(类别)对行进行排序,以便显示类别 A、B、C 的条目。
我尝试在 foreach 循环中使用 sort() 命令,但没有成功。
有什么想法吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以使用下一种方法:
$split_lines = []; // first - split lines and put them into array foreach ($lines as $line) { $split_lines[] = explode('||', $line); } // sort array by function usort($split_lines, fn($a,$b)=>$a[2]$b[2]); // show array as table foreach ($split_lines as $line) { echo '';
echo ''.$line[0].' ';
echo ''.$line[1].' ';
echo ''.$line[2].' ';
echo ' ' . PHP_EOL;
}在线运行 PHP
您可以仅使用两个 for 循环来实现它。