0

This is my table which I am displaying using PHP from a CSV file

1

I want to sort it such that all rows of m1 come first, then a blank line, then m2 and so on.

This is my code which i use to display the CSV file as a table.

<?php
$filename = basename(__FILE__, ".php");
$f = fopen("$filename.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</tbody></table></body></html>";
?>

1 Answer 1

2

You can use below code to render your table. This is how it works:

  1. It creates a data array first form the CSV file

  2. then it sorts the first column ascending order

  3. loop through each line and render table

     $mdarray = array();
     $filename = basename(__FILE__, ".php");
     $f = fopen("$filename.csv", "r");
    
     while (($line = fgetcsv($f)) !== false) {
     {
        array_push($mdarray, $line);
     }
     fclose($f);
    
     foreach ($mdarray as $key => $row) {
        $names[$key]  = $row[0];
     }
    
     array_multisort($names, SORT_ASC, $mdarray);
     //array_multisort(array_column($mdarray, 0), SORT_ASC, $mdarray);//php version >=5.5
    
     foreach ($mdarray as $line) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
    
       echo "<hr>"; // blank line
    }
    
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you so much, but there's an error Call to undefined function array_column() and it doesn't show anything at all.
Which php version are you using?
I have updated my code to support older version of php
@Gaurav please don't forget to mark it as accepted one so that others can get help from it in the future
is the open bracket just after the while statement necessary?!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.