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

时间:2017-01-31 01:42:09

标签: php

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

如果我有这个文本文件,我在php中读取,如何从第二行开始排序,第一行是文件的标题。这样文件就会打印出来......

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

我使用fopen阅读该文件,使用$content将其放入fread,使用新行使用explode。我可以看到行数组,但无法弄清楚如何对它进行排序。任何建议将不胜感激。

2 个答案:

答案 0 :(得分:0)

大部分解决方案都在评论中回答了您的问题。所有这些都让你在寻找类似的东西:

<?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)."\n"); //write other elements to new file on own line
}
fclose($newf); //close the file
?>

答案 1 :(得分:0)

试试这个:

#bio {
  float: left;
}

输出myfile.txt

$data = trim(file_get_contents('sort_test.txt'));
$data = explode("\n", $data);
$array_order = array();
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation, "w");
for ($i = 0; $i < count($data); $i++) {
   ($i > 0) ? $array_order[$i] = $data[$i] : fwrite($file, $data[0]); 
}
sort($array_order);
$data = implode("\n", $array_order);
fwrite($file, $data);
fclose($file);
echo 'file created - location::' . $fileLocation;

也许新文件(myfile.txt)需要对您要写入的目录具有写权限,在我的情况下,该文件已存储到C:/.../ htdocs / myfile.txt