Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort text file (.txt) numerically

Thank you for taking the time to read this and I will appreciate every single response no mater the quality of content. :)

Using php, I'm trying to create a script which will numerically sort a text file (.txt) in ascending order (lowest to highest). Each entry within the text file is on a new line, therefore I'd like the lines to be numerically sorted. If possible, once it has been numerically sorted, I'd like the data to be written into another text file, titled "newtime.txt" within the same directory. Of course, if possible. ;)

The main part I'm struggling with is that the content within the text file isn't static (e.g. contain x number of lines/words etc.) Infact, it is automatically updated with several lines. Therefore, I'd like all the lines to be updated numerically.

The text file follows the structure:

2 aullah1
12 name
7 username

Of course, which is regularly updated with more lines. Will it be possible to numerically sort the lines? Also, I plan on using a Cron Job to repeat the script every 5 minutes. ;)

P.S. What will happen if there are two same numbers? Will it then go onto sorting out the data alphabetically?

All assistance is appreciated and I look forward to your replies; thank you. :) If I didn't explain anything clearly and/or you'd like me to explain in more detail, please reply. :)

Thank you.

like image 260
aullah Avatar asked Aug 26 '10 17:08

aullah


2 Answers

Assuming you are working with a reasonable number of lines (thousands, not millions) this should be sufficient. If you have very large files, you may run into memory issues using file():

<?php

$data = file($file_path);
natsort($data);
file_put_contents($new_file_path, implode("\n", $data));

You could replace the single file_put_contents with a looped fwrite() for each element in $data.

natsort() will sort the numerics correctly (as opposed to asort() which will put 10 before 2). For matching numerics, it will sort as you expect, comparing the rest of the string.

natsort(), file()

like image 79
jasonbar Avatar answered Nov 07 '22 16:11

jasonbar


You can do this easily by

Reading the file into an array:

$lines = file($path_to_file);

Sort the array:

natsort($lines);

Write the array back to a new file:

file_put_contents($path_to_new_file, implode(PHP_EOL, $lines));
like image 45
Mischa Avatar answered Nov 07 '22 15:11

Mischa