我使用 PHP 訪問文本文件中包含的一些數(shù)據(jù)。
以下是文本文件 (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 文件內(nèi)容的 PHP 代碼。 我訪問該文件并循環(huán)遍歷每一行以提取三個部分:
<?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>
我需要根據(jù)第三個字段(類別)對行進行排序,以便顯示類別 A、B、C 的條目。
我嘗試在 foreach 循環(huán)中使用 sort()
命令,但沒有成功。
有什么想法嗎?
您可以使用下一種方法:
$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 ' ' . PHP_EOL; }'.$line[0].' '; echo ''.$line[1].' '; echo ''.$line[2].' '; echo '
您可以僅使用兩個 for 循環(huán)來實現(xiàn)它。
ID | TEXT | CATEGORY | '.$id.' | '; echo ''.$text.' | '; echo ''.$category.' | '; echo ''; } ?>
---|