dsgfdgh14569 2017-09-17 06:58
浏览 39
已采纳

严格使用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>";
?>
  • 写回答

1条回答 默认 最新

  • douken0530 2017-09-17 07:18
    关注

    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
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料