PHP: display entries from Database in groups of five?

為{幸葍}努か 提交于 2019-12-06 01:07:59

I find array_chunk() to be pretty useful for this kind of thing.

// pull all the records into an array
$query = mysql_query('SELECT * FROM mytable');
$rows = array();
while ($row = mysql_fetch_array($query)) {
  $rows[] = $row;
}

// this turns an array into an array of arrays where each sub-array is
// 5 entries from the original
$groups = array_chunk($rows, 5);

// process each group one after the other
$start = 1;
foreach ($groups as $group) {
  $end = $start + 4;

  // $group is a group of 5 rows. process as required
  $content = implode(', ', $group);

  echo <<<END
<div class="$start-$end">$content</div>

END;
  $start += 5;
}

You can of course do this without reading them all in first but if you're going to read them all anyway, it doesn't make much difference and the above version will probably be far more readable than implementing the appropriate break condition(s) as you read the rows from the DB.

Dunno if i understand the question right but if u want to group all the result in groups of 5:


$i =1;    
while ($row = mysql_fetch_array($query)) {
 echo $row['name']."\n";
 if ($i % 5 == 0)
 {
   echo 'hr'; // Or any other separator you want
 }
 $i++;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!