Home > OS >  sorting PHP array by element in a foreach loop
sorting PHP array by element in a foreach loop

Time:06-13

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?

CodePudding user response:

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>

CodePudding user response:

You can use next approach:

$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 '<tr>';
    echo '<td>'.$line[0].'</td>';
    echo '<td>'.$line[1].'</td>';
    echo '<td>'.$line[2].'</td>';
    echo '</tr>' . PHP_EOL;
}

run PHP online

  • Related