【问题标题】:PHP reading next line in text file while using lazy loading?PHP在使用延迟加载时读取文本文件中的下一行?
【发布时间】:2020-01-03 09:04:57
【问题描述】:

我有一个要逐行读取的文本文件。对于每一行,我还需要下一行的值,所以我需要一些东西来读取当前行中的下一行。

我在这里阅读了许多答案,我可以使用foreach 循环来做到这一点,但它需要提前读取整个文件。我正在寻找一些只能根据需要阅读的内容。

这是迄今为止我使用 SplFileObject 得到的结果。

$file = new \SplFileObject($textFile);
$lastNumber = 500;

while (!$file->eof()) {
    $currentLine = $file->fgets();

    $currentNumber = intval($currentLine);
    $file->next();

        if ($file->eof()) {
            $nextNumber = intval($lastNumber);
        } else {
            $nextNumber = intval($file->fgets()) - 1;
        }

        echo $currentNumber . ', ' . $nextNumber . '<br>';

}

假设我有一个包含这样行的文本

0
100
200
300
400

我希望他们像这样打印出来

0, 99
100, 199
200, 299
300, 399
400, 500

但我的代码隔行跳过

0, 99
200, 299
400, 500

我的猜测是我的 while 循环和 $file-&gt;next() 每个循环都将行移动 1,这就是跳过的原因。但是没有next() 调用,我不知道如何获取下一行的值。我该如何解决这个问题?

【问题讨论】:

  • 您可以创建一个简单的堆栈。在第一次运行之前在上面放两行,然后再循环。然后开始循环,你有当前和下一个可用。在循环本身中,从堆栈中拉电流,读取下一行并推送到堆栈。

标签: php text-files splfileobject


【解决方案1】:

使用这个 PHP 代码解决方案。

  $textFile = 'text.txt';

  $file = new SplFileObject($textFile);
  $lastNumber = 500;

  foreach ($file as $lineNumber => $line) {
    $currentNumber = intval($file->current());

    if ($lineNumber === 0) {
      $previousNumber = $currentNumber;
      continue;
    } else {
      $nextNumber = $currentNumber - 1;
      echo $previousNumber . ', ' . $nextNumber . '<br>';

      $previousNumber = $currentNumber;

      if ($file->eof()) {
        $nextNumber = intval($lastNumber);
        echo $currentNumber . ', ' . $nextNumber . '<br>';
      }
    }
  }

【讨论】:

  • 这会延迟加载吗?
  • 延迟加载是什么意思?这是 PHP 而不是 JAVASCRIPT。请说明您想要实现的确切功能。
猜你喜欢
  • 2019-12-20
  • 2020-10-31
  • 2013-10-27
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
  • 1970-01-01
相关资源
最近更新 更多