3

我需要每十行在一个 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(),因此它的行来自文件。

4

4 回答 4

3

这应该有效:

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

参考:

于 2010-10-14T14:51:43.690 回答
1
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>";
于 2010-10-14T14:49:13.493 回答
0

通过快速谷歌搜索:

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,做你需要做的。

于 2010-10-14T14:48:30.100 回答
0

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

$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;
  }
}
于 2010-10-14T14:50:07.007 回答