简体   繁体   中英

PHP read in every 10 out of 100 lines

I'm trying to read in a text file of 5000 lines. However I only want to get the first 10 lines of every 100 lines. So line 1-10, line 101 - 110, line 200 - 210 etc. I just cant figure out the logic to use.

$count = count(file($text))

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

Use % 100 and only print lines where $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
  }
}

A sample of how the logic works:

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

You can easily do this with an SPLFileObject , as long as you know how many lines are in the file:

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

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

Now you know there are $lines number of lines in the file. If that is static, say 5000, just initialize $lines to 5000. If it's not, let's round that down to the nearest 100:

$lines -= ($lines % 100);

Now, we just loop over every hundred, seek to the grouping of 10, and grab the data we want:

$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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM