PHP Sort Text File (.txt) Numerically

Thank you for taking the time to read this, and I will be grateful for every answer that is not responsible for the quality of the content. :)

Using php, I am trying to create a script that will sort a text file (.txt) in ascending order (from lowest to highest). Each entry in the text file is on a new line, so I want the lines to be sorted by numbers. If possible, after it has been numerically sorted, I would like the data to be written to another text file called "newtime.txt" in the same directory. Of course, if possible .;)

The main part I'm struggling with is that the content in the text file is not static (for example, it contains x the number of lines / words, etc.). Infact, it automatically updates in a few lines. Therefore, I would like all rows to be updated numerically.

The text file follows the structure:

2 aullah1
12 name
7 username

Of course, this is updated regularly with lots of lines. Will it be possible to sort the lines numerically? In addition, I plan to use Cron Job to repeat the script every 5 minutes .;)

PS What happens if there are two identical numbers? Then he will proceed to sort the data alphabetically?

All help is appreciated, and I look forward to hearing from you; Thank you. :) If I didn’t explain anything clearly and / or you would like me to explain in more detail, answer. :)

Thank.

+5
4

, (, ), . , , file():

<?php

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

file_put_contents fwrite() $data.

natsort() ( asort(), 10 2). , , .

natsort(), file()

+5

:

$lines = file($path_to_file);

:

natsort($lines);

:

file_put_contents($path_to_new_file, implode(PHP_EOL, $lines));
+5
<?php
$lines = file("time.txt");
natsort($lines);
file_put_contents("newtime.txt", implode("\n", $lines));
?>
+3

, , , , . Linux ( exec, PHP), ( , ):

exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);

, bash sort, . , :

exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);
exec("rm " . $pathToOriginalFile);
exec("mv " . $pathToSortedFile . " " . $pathToOriginalFile);

, -n (--numeric-sort).

exec("sort " . $pathToOriginalFile . " > " . $pathToSortedFile);

3 , 10 .

http://www.computerhope.com/unix/usort.htm

, .

+1
source

All Articles