【问题标题】:how to read all second lines from txt files with php and put them in 1 variable如何使用php从txt文件中读取所有第二行并将它们放入1个变量中
【发布时间】:2019-12-04 19:11:44
【问题描述】:

我有很多 .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);

【问题讨论】:

  • 你是指所有偶数行,还是每个文件的第 2 行?
  • 我的意思是每个文件的第 2 行
  • 不确定,但你可以试试$lines = file($dir . $file);

标签: php arrays file sorting


【解决方案1】:

将第二行放入一个全局数组中,然后根据需要使用 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);
}

【讨论】:

  • print_r 给我这个输出:Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 它应该是Array ([0]=>sec.line [1]=>sec.line [2]=>sec.line and so on...
  • 我认为问题可能是 $file 不包含 dir 路径,并且由于这些文件位于消息文件夹中,因此您需要将 $dir 添加到文件路径中。查看我的编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多