首页 > 解决方案 > 如何使用php从txt文件中读取所有第二行并将它们放入1个变量中

问题描述

我有很多 .txt 文件,其中有几行内容。要获取文件夹消息中的所有 txt 文件,我使用以下代码:

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

    }
}

要从 txt 文件中获取第二行,我知道我可以使用它:

$lines = file($file);
$secondline = $lines[1];

但是我怎样才能从所有 txt 文件中获取所有第二行并将其放入变量中,以便我可以对其进行排序?就像是。rsort($all_secondlines_allfiles);

标签: phparraysfilesorting

解决方案


将第二行放入全局数组,然后使用 r/sort() 函数根据需要对其进行排序。

$globalArray = [];

$dir = 'messages/';
if ($dh = opendir($dir)) {
    while(($file = readdir($dh))!== false){
        if ($file != "." && $file != "..") { // This line strips out . & .. 
            $lines = file($dir.$file);
            $secondline = $lines[1];    
            $globalArray[] = $secondline;                 
        }
    }
sort($globalArray);
print_R($globalArray);
}

推荐阅读