I am using PHP to access some data contained in a text file.
The following is an example of a text file (myfile.txt) - each line has three fields separated by ||
:
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
This is the PHP code I use to display the contents of a txt file in a simple HTML table. I access the file and loop through each line to extract the three parts:
<?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>
I need to sort the rows based on the third field (category) so that entries for categories A,B,C are displayed.
I tried using the sort()
command inside a foreach loop, but without success.
Any ideas?
You can use the next method:
Run PHP online
You can implement it using just two for loops.