sorting PHP array by element in a foreach loop

Issue

I use PHP to access some data which is contained in a text file.
Here is a sample of the 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 show the contents of the txt file in a simple HTML table.
I access the file and I 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 lines according to the third field (category), so as to show the entries of category A, then B and then C.

I tried to use the sort() command within the foreach loop, with no success.
Any ideas?

Solution

You can achive it using two for loop only.

   <?php
$lines = file("myfile.txt");
?>
<table>
 <thead>
  <tr>
   <th>ID</th>
   <th>TEXT</th>
   <th>CATEGORY</th>
  </tr>
 </thead>
 <tbody>
<?php

$listOfFiles = array();
foreach ($lines as $line) {
    list($id,$text,$category) = explode('||', $line);
    array_push($listOfFiles,$category."||".$text."||".$id);
}

sort($listOfFiles);

foreach($listOfFiles as $line)
{
    list($category,$text,$id) = explode('||', $line);
    echo '<tr>';
    echo '<td>'.$id.'</td>';
    echo '<td>'.$text.'</td>';
    echo '<td>'.$category.'</td>';
    echo '</tr>';
}

?>
 </tbody>
</table>

Answered By – gsharew

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published