【问题标题】:displaying multiple lines of a file, never repeating显示文件的多行,从不重复
【发布时间】:2010-10-14 14:40:37
【问题描述】:

我需要每十行在一个 div 中回显它们。

示例:

<div class='return-ed' id='1'>
line 1
line 2
...
line 9
line 10
</div>

<!-- next group of lines -->

<div class='return-ed' id='2'>
line 11
line 12
...
line 19
line 20
</div>

有人知道怎么做吗?

数组来自file(),所以它的行来自一个文件。

【问题讨论】:

    标签: php lines


    【解决方案1】:

    这应该可行:

    $blocks = array_chunk(file('path/to/file'), 10);
    foreach($blocks as $number => $block) {
        printf('<div id="%d">%s</div>', 
                $number+1, 
                implode('<br/>', $block));
    }
    

    参考资料:

    【讨论】:

    • array_chunk 默认有bool $preserve_keys = false,因此文件编号将按块重新编号。
    【解决方案2】:
    echo '<div class="return-ed" id="1">';
    $lineNum = 0;
    foreach ($lines as $line) {
        if ($lineNum && !($lineNum % 10)) {
            echo '</div><div class="return-ed" id="'.($lineNum/10+1).'">';
        }
        echo $line."<br />";
        $lineNum++;
    }
    echo "</div>";
    

    【讨论】:

    • 使用% 比我的更优雅,但除了最后一个循环之外,其他所有循环都没有结束&lt;div&gt;
    • 是的。我不应该在早上第一件事就直接在 textarea 中输入代码。我已经添加了关闭 div。
    【解决方案3】:

    通过谷歌快速搜索:

    http://www.w3schools.com/php/php_file.asp

    逐行读取文件

    fgets() 函数用于从文件中读取一行。

    注意:调用此函数后,文件指针已移至下一行。

    来自 W3 学校的示例:

    下面的例子

    逐行读取文件,直到到达文件末尾:

    <?php
    $file = fopen("welcome.txt", "r") or exit("Unable to open file!");
    //Output a line of the file until the end is reached
    while(!feof($file))
      {
      echo fgets($file). "<br />";
      }
    fclose($file);
    ?>
    

    您需要做的就是让您的计数变量在该 while 循环中最多计数 10。一旦达到 10,做你需要做的。

    【讨论】:

      【解决方案4】:

      假设你的行在一个你正在回显的数组中,这样的事情会起作用:

      $count = 0;
      $div = 1;
      foreach($lines as $line){ //or a for loop, whatever you're using
        if(0 == $count){
          echo "<div id='$div'>";
        }
      
        $count++;
        echo $line;
      
        if(10 == $count){
          echo "</div>";
          $count = 0;
        }
      }
      

      【讨论】:

      • 我想你的意思是foreach ($lines as $line)
      • @webbiedave - 确实。看来早晨很危险。已更新。
      • 呃...我会选择其他答案之一 - 并不是说​​我不欣赏“接受”。你猜这个只是让逻辑很明显?
      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      相关资源
      最近更新 更多