Sort PHP array element-wise in foreach loop
P粉567281015
P粉567281015 2024-03-31 10:17:19
0
2
468

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粉567281015
P粉567281015

reply all(2)
P粉373596828

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

P粉897881626

You can implement it using just two for loops.


'; echo ''; echo ''; echo ''; echo ''; } ?>
ID TEXT CATEGORY
'.$id.''.$text.''.$category.'
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template