严格使用php或javascript按第一列第1列对CSV文件进行排序

严格使用php或javascript按第一列第1列对CSV文件进行排序

问题描述:

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>
";
}
fclose($f);
echo "
</tbody></table></body></html>";
?>

这是我从CSV文件中使用PHP显示的表格 p>

p>

我想对它进行排序,以便m1的所有行 首先是空白行,然后是m2,依此类推。 p>

这是我用来将CSV文件显示为表的代码。 p>

 &lt;?php 
 $ filename =  basename(__ FILE __,“。php”); 
 $ f = fopen(“$ filename.csv”,“r”); 
while(($ line = fgetcsv($ f))!== false){
  echo“&lt; tr&gt;”; 
 foreach($ line as $ cell){
 echo“&lt; td&gt;”  。  htmlspecialchars($ cell)。  “&lt; / td&gt;”; 
} 
 echo“&lt; / tr&gt; 
”; 
} 
 nclclose($ f); 
echo“
&lt; / tbody&gt;&lt; / table&gt;&lt;  / body&gt;&lt; / html&gt;“; 
?&gt; 
  code>  pre> 
  div>

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>
    ";
    
       echo "<hr>"; // blank line
    }