Search code examples
phptext-filesfwrite

How to sort a data in txt file?


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!';

Solution

  • $data = trim(file_get_contents('file'));
    $data = explode("\n",$data);
    sort($data,SORT_NUMERIC);
    $data = implode("\n",$data);