3

我正在尝试读取 5000 行的文本文件。但是我只想得到每 100 行的前 10 行。所以第 1-10 行,第 101 - 110 行,第 200 - 210 行等。我只是想不出要使用的逻辑。

$count = count(file($text))

for ($i = 0; $i < $count; $i++) 
 {
 $test = fgets($f_text)
 }
4

3 回答 3

5

使用% 100并且仅打印$n % 100 > 0 && $n % 100 <= 10.

$lines = file($text);
foreach ($lines as $n => $line) {
  if ($n % 100 > 0 && $n % 100 <= 10) {
     echo $line; // or whatever
  }
}

逻辑如何工作的示例:

foreach (range(0,250) as $n => $line) {
  if ($n % 100 >= 1 && $n % 100 <= 10 ) {
    echo $i . "\n";
  }
}

1 2 3 4 5 6 7 8 9 10 101 102 103 104 105 106 107 108 109 110 201 202 203 204 205 206 207 208 209 210
于 2012-07-29T23:51:14.363 回答
1

SPLFileObject只要您知道文件中有多少行,您就可以使用 轻松做到这一点:

$file = new SplFileObject( $filename, "r");

$lines = 0;
while ( !$file->eof()) {
   $file->fgets();
   $lines++;
}

现在您知道文件中有$lines多少行。如果那是静态的,比如 5000,只需初始化$lines为 5000。如果不是,让我们将其四舍五入到最接近的 100:

$lines -= ($lines % 100);

现在,我们只循环每 100 个,寻找 10 个分组,然后获取我们想要的数据:

$data = array();
for( $i = 0; $i < $lines; $i += 100) {
    $file->seek( $i);
    for( $j = 0; $j < 10; $j++) {
        $data[] = $file->fgets();
    }
}

With this solution, you never load the whole file into memory, which will save resources when dealing with large files. Also, if you know the size of the file beforehand, you will only read the lines of data that you require.

于 2012-07-29T23:56:11.243 回答
0

Based on both other answers, probably the most memory-efficient way to do it:

foreach(new SplFileObject($filename) as $n => $line)
    if($n % 100 < 10)
        echo $line;
于 2012-07-30T00:07:55.540 回答