如何对txt文件中的数据进行排序?
我已经生成了txt文件。如何按 |
之前的第一个数字对其中的行进行排序?
它的结构如下:
1|5
4|7
2|3
3|1
我尝试这样,但它显示错误。完整代码:
$str='';
foreach ($_POST['answer'] as $num => $answer) {
$str.="$num|".rtrim($answer)."\r\n";
}
$data = explode("\n",$str);
sort($data,SORT_NUMERIC);
$date=date('y-m-d_H-i-s');
$fp=fopen("output/".$date."_out.txt", "w+");
$write=fwrite($fp, $data);
fclose($fp);
if ($write) echo 'Done!';
I have generated txt file. How to sort the lines in it by first number before |
?
It have structure like:
1|5
4|7
2|3
3|1
I try like this, but it's show error. Full code:
$str='';
foreach ($_POST['answer'] as $num => $answer) {
$str.="$num|".rtrim($answer)."\r\n";
}
$data = explode("\n",$str);
sort($data,SORT_NUMERIC);
$date=date('y-m-d_H-i-s');
$fp=fopen("output/".$date."_out.txt", "w+");
$write=fwrite($fp, $data);
fclose($fp);
if ($write) echo 'Done!';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我遇到同样的问题时,这是迄今为止我发现的最快、最优雅的解决方案。
如果您使用的是 Linux(PHP 配置中允许使用 exec),您可以执行以下操作(前提是您想按数字对文件进行排序):
基本上,执行 bash 命令 sort 对文件中的行进行数字排序。
如果您想将数据保留在原始文件中,请执行以下操作:
如果您想要按字母顺序排序,只需排除 -n (--numeric-sort) 选项。
对我来说,该命令大约需要 3 秒才能对服务器上文件中的 1000 万行进行排序。
您可以在此处找到有关排序的更多信息 http://www.computerhope.com/unix/usort.htm< /a>
希望有帮助。
This is by far the fastest and most elegant solution that I have found, when I had the same problem.
If you're on Linux (with exec allowed in PHP configuration) you can do the following (provided you want to sort files numerically):
Basically, execute bash command sort that sorts the lines in a file numerically.
If you want to keep the data in the original file do this:
If you want an alphabetical sort just exclude -n (--numeric-sort) option.
For me the command took about 3 seconds to sort 10 million lines in the file on the server.
You can find more about sort here http://www.computerhope.com/unix/usort.htm
Hope it helps.