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

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)