dongzhiju0324 2017-01-31 01:42
浏览 129
已采纳

我怎样才能在php中对文本文件进行排序

english, lang1, lang2
rat, rat_lang1, rat_lang2
ball, ball_lang1, ball_lang2
air, air_lang1, air_lang2

If I have this text file I read in php, how can I sort it starting the second line, the first line being the heading of the file. So that the file will print out like..

english....
air....
ball...
rat....

I read the file using fopen, put it in $content using fread, used explode with new line. I can see the array of lines but cannot figure out how to sort it. Any suggestions would be appreciated.

  • 写回答

2条回答 默认 最新

  • douzi9430 2017-01-31 02:15
    关注

    Much of this solution was answered within the comments in response to your question. All put together you're looking for something like:

    <?php
    $f = file("text.txt"); //read the text file into an array
    $newf = fopen("newtext.txt", "w+"); //open another file
    $header = $f[0]; //store the first element of the array as $header
    echo $header."<br>"; //and echo the header
    fwrite($newf, $header); //write the header to the new file
    array_shift($f); //then remove the first element of the array i.e. the header
    sort($f); //sort the array (no flag param = alphabetical sort)
    foreach($f as $line){ //loop through the sorted array
        echo $line."<br>"; //print each element as it's own line
        fwrite($newf, trim($line)."
    "); //write other elements to new file on own line
    }
    fclose($newf); //close the file
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?