How to alphabetize using php

I have 2 text files containing several words, for example:

File 1

Aarhus
Abbott
Abbott's
Abel
Abelian
Abelson
Abelson's
Aberdeen
Aberdeen's

File 2

Acapulco
Ackerman
Acta
Adam
Adams
Adamson

This is just an example list, files contain more than 10,000 entries, and words can be placed in any order. but one thing that makes it easier is that each line contains only one word. Now I know how to read these values ​​using php one by one, but I cannot figure out how to combine these two files and sort them alphabetically. Can someone suggest me how to do the sorting?

EDIT

One more note: as you can see, there are several words containing a single quote '. Please offer me answers that consider this option when sorting.

FURTHER IMAGE

. , , .

+3
4
$entries = array_merge(
             file('file_one', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
             file('file_two', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
           );
$entries = array_unique($entries);
sort($entries);
+7
$lines = array_merge(file('file1.txt'), file('file2.txt'));
sort($lines);
+2

Store both files in an array, then use php sort ? .-.

0
source

Since individual files are individually sorted, you can perform a merge sort type.

Here is some pseudo code:

A -> File 1
B -> File 2
C -> SortedFile
While(A and B have lines left){
  Left = NextLineFromA
  Right= NextLineFromB
  If = Left < Right // strcmp(...)
    Write Left to C
  Else
    Write Right to C
}
// Now either A or B will have lines left
Write all lines left from A||B to C

Or you can read them, do array_merge () and then sort ()

I think it will be faster because you do not need to re-sort everything when you call sort ()

The php collation function is a quick O (n log (n)) collation algorithm, and thus O (n)

0
source

All Articles