问题描述
我有两行数据文件(两行只是为了我的例子,实际上,该文件可以包含数百万行),我使用带有偏移量的 SplFileObject 和 LimitIterator.但是这种组合在某些情况下会产生奇怪的行为:
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;
}
输出为:01
但是当 $offset 设置为 1 时,输出为空白(foreach 不迭代任何行).
But with $offset set to 1, output is blank (foreach doesn't iterate any line).
我的数据文件包含:
{"generatedAt":1434665322,"numRecords":"1}
{"id":"215255","code":"NB000110"}
我做错了什么?
谢谢
推荐答案
必需:
使用 SplFileObject
处理来自以下位置的多个记录:
Use SplFileObject
to process a number of records from:
- 给定的起始记录编号
- 对于给定数量的记录或直到
EOF
.
问题是 SplFileObject
对文件中的 last record
感到困惑.这会阻止它在 foreach
循环中正常工作.
The issue is that SplFileObject
gets confused as regards the last record
in the file. This prevents it working correctly in foreach
loops.
此代码使用 SplFileObject
和跳过记录"和处理记录".唉,它不能使用 foreach
循环.
This code uses the SplFileObject
and 'skip records' and 'processes records'. Alas, It cannot use foreach
loops.
- 从文件开头跳过一些记录 (
$offset
). - 处理给定数量的记录或以文件结尾为单位 (
$recordsToProccess
)
代码:
<?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();
}
这篇关于SplFileObject + LimitIterator + 偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!