Home > Software design >  sorting table row data with php
sorting table row data with php

Time:05-11

<table >     
 <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?

CodePudding user response:

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

  • Related