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 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题