search

Home  >  Q&A  >  body text

Sort PHP array element-wise in foreach loop

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?

P粉567281015P粉567281015236 days ago396

reply all(2)I'll reply

  • P粉373596828

    P粉3735968282024-04-01 09:13:55

    You can use the next method:

    $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;
    }

    Run PHP online

    reply
    0
  • P粉897881626

    P粉8978816262024-04-01 00:24:30

    You can implement it using just two for loops.

    
    ';
        echo '';
        echo '';
        echo '';
        echo '';
    }
    
    ?>
     
    ID TEXT CATEGORY
    '.$id.''.$text.''.$category.'

    reply
    0
  • Cancelreply