【问题标题】:how to sort txt files in php based on the second line in each txt file如何根据每个txt文件中的第二行对php中的txt文件进行排序
【发布时间】:2020-04-01 04:12:05
【问题描述】:

我有几个.txt 文件,其中的代码行。每个txt文件的名字都有一个唯一的id:

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

所有的txt文件都在messages文件夹中,我通过这段代码阅读了所有的文件:

// 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
}

所以 var $entrylist 是一个包含所有 txt 文件的数组。 print_r($globalArray) 向我展示了基于姓氏的排序数组

为了输出 txt 文件,我使用了 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...

我的问题:

如何根据每个文件的第二行(姓氏)对foreach中的所有txt文件进行排序?

所以我想要实现的是:sort($entrylist) based on second line of each txt file...

【问题讨论】:

    标签: php arrays sorting foreach


    【解决方案1】:

    在存储文件名时,最好使用名称作为姓氏数组中的键。然后,您可以对数据进行排序,使键与数据保持一致,以便文件名保留在排序后的输出中(使用asort() 而不是sort())。然后您可以foreach() 覆盖结果,索引是您的文件名...

    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;
        }
    }
    

    我非常糟糕的测试数据给出了...

    Array
    (
        [10.csv] => jones
    
        [1.csv] => blogs
    
    )
    1.csv
    10.csv
    

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2012-05-23
      • 2016-07-31
      • 2014-01-06
      • 2020-08-04
      • 2018-12-15
      • 2017-07-16
      • 2018-11-20
      • 1970-01-01
      相关资源
      最近更新 更多