dongqiao9015 2015-06-19 07:37
浏览 100
已采纳

SplFileObject + LimitIterator + offset

I have data file with two lines (two lines just for my example, in real, that file can contain millions of lines) and I use SplFileObject and LimitIterator with offseting. But this combination have strange behaviour in some cases:

$offset = 0;
$file = new \SplFileObject($filePath);
$fileIterator = new \LimitIterator($file, $offset, 100);
foreach ($fileIterator as $key => $line) {
  echo $key;
}

Output is: 01

But with $offset set to 1, output is blank (foreach doesn't iterate any line).

My data file contain this:

{"generatedAt":1434665322,"numRecords":"1}
{"id":"215255","code":"NB000110"}

What I'm doing wrong?

Thanks

  • 写回答

1条回答 默认 最新

  • doutang1992 2015-06-19 10:38
    关注

    Required:

    Use SplFileObject to process a number of records from:

    • a given start record number
    • for a given number of records or until EOF.

    The issue is that SplFileObject gets confused as regards the last record in the file. This prevents it working correctly in foreach loops.

    This code uses the SplFileObject and 'skip records' and 'processes records'. Alas, It cannot use foreach loops.

    • Skip a number of records from the start of the file ($offset).
    • Process a given number of records or unit the end of file ($recordsToProccess)

    The code:

    <?php
    
    $filePath = __DIR__ . '/Q30932555.txt';
    // $filePath = __DIR__ . '/Q30932555_1.txt';
    
    $offset = 1;
    $recordsToProcess = 100;
    
    $file = new \SplFileObject($filePath);
    
    // skip the records
    $file->seek($offset);
    
    $recordsProcessed = 0;
    while (     ($file->valid() || strlen($file->current()) > 0)
             &&  $recordsProcessed < $recordsToProcess
           ) {
        $recordsProcessed++;
        echo '<br />', 'current: ', $file->key(), ' ', $file->current();
        $file->next();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line