Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sorting table row data with php

<table class="tbmed">     
 <tr> 
  <th>R1</th> 
  <th>R2</th>
  <th>R3</th>
  <th>R4</th>
 </tr>


<?php
 include ("config.php");
  $sql = "SELECT id, r1, r2, r3, r4  FROM table order by id DESC ";         
  
  $result = $conn->query($sql);
  if ($result->num_rows > 0) {
 
 while($row = $result->fetch_assoc()) 
   {
        echo "<tr><td>". 
        '.'.$row["r1"].'.' . "</td><td>".
        '.'.$row["r2"].'.' . "</td><td>". 
        '.'.$row["r3"].'.' . "</td><td>". 
        '.'.$row["r4"].'.' .  
        "</td></tr>";
    }
echo "</table>";
} else { echo "0 results"; }
$conn->close();

?>     

I have some numerical data which are all positive, there may be repetitive values though.
The above code gives the results like so:

R1 R2 R3 R4 
10 2  5  5
4  4  1  9
....

I’d like to sort the output in each row of the data table, and the result would be :

R1 R2 R3 R4 
2  5  5  10
1  4  4  9

How can I achieve this ? can someone help me please?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use fetch_array instead fetch_assoc and apply sort function before output. Somehow like next:

if ($result->num_rows > 0) {
    while($row = $result->fetch_array(MYSQLI_NUM)) 
    {
        sort($row);
        echo '<td>';
        echo implode('</td><td>', $row);
        echo '</td>' . PHP_EOL;
    }
}

Try code online

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading