john
john

Reputation: 1273

how to sort txt files in php based on the second line in each txt file

I have several .txt files in which lines of code. The name of each txt file has a unique id:

20191205140624.txt
20191206140309.txt
and so on...

All the txt files are in the messages folder and i read all of them by this code:

// read all files in messages folder
$dir = 'messages/';
if ($dh = opendir($dir)) {
    while(($file = readdir($dh))!== false){
        if ($file != "." && $file != "..") { // This line strips out . & ..         
            $entrylist[] = $file;   

            $lines = file($dir.$file);
            $secondline = $lines[1]; // grab the second line   
            $globalArray[] = $secondline;   // put all second lines in an array         
        }

    }   
    sort($globalArray); // sort array
    print_r($globalArray); // show me the array
}

So var $entrylist is an array of all txt files. And print_r($globalArray) shows me the sorted array based on the surname

To output the txt files, i use a foreach:

// sort array
sort($entrylist);

foreach($entrylist as $file){
    $entryfiles = 'messages/'.$file;
    $lines = file($entryfiles, FILE_IGNORE_NEW_LINES);// filedata into an array
    $file_id = $lines[0]; // file id
    $surname= $lines[1]; //  surname
    $address= $lines[3];
    and so on...

Myquestion:

How can i sort all txt files in the foreach based on the second line(surname) of each file?

So what i want to achieve is something like: sort($entrylist) based on second line of each txt file...

Upvotes: 1

Views: 150

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

When storing the name of the file, you would be better off using the name as the key in the array for the surname. Then you can sort the data keeping the keys with the data so that the file name stays in the sorted output (using asort() instead of sort()). You can then foreach() over the result and the index is your file name...

if ($dh = opendir($dir)) {
    while(($file = readdir($dh))!== false){
        if ($file != "." && $file != "..") { // This line strips out . & ..
            $lines = file($dir.$file);
            $secondline = $lines[1]; // grab the second line
            $globalArray[$file] = $secondline;   // put all lines in array indexed by file name
        }

    }
    asort($globalArray); // sort array preserving keys
    print_r($globalArray); // show me the array

    foreach($globalArray as $file => $surname){

        echo $file.PHP_EOL;
    }
}

which my very bad test data gives...

Array
(
    [10.csv] => jones

    [1.csv] => blogs

)
1.csv
10.csv

Upvotes: 2

Related Questions