Search code examples
phpsortingquicksort

How to sort a CSV file in PHP without loading the entire file into memory?


I'm trying to write a PHP script which will handle sorting of a CSV file by one or multiple columns and outputting the result to another file.

Is there a way to sort the CSV file without loading it entirely into memory?


Solution

  • No there is no reasonable way. You need the data in memory to compare and write in a file.

    You could try a bubblesort if you know the length of each line. Read one line of origin and last line of a new "ordered" file. Compare them and append or prepend in new file. After this iteration do again with the new file as origin until it is sorted.

    You should use a database like MySQL.