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条)

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。