Grouping items in php
I have a problem with sorting items in table in PHP. Here is what I want to achieve :
Item Item Item
Item Item Item
Item Item Item
Item Item Item
Item Item Item
How I mean to achieve this, well since I have a for each loop I can insert counter, and say after 5th item is listed write to another column, the thing is I'm not good with tables, I've tried something like :
for(...)
$counter++;
if(($counter%5) == 0){
echo "";
}
Not happening .. I hope you understood 开发者_StackOverflow社区what I meant .. tnx
I assume you want this:
Item1 Item6 Item11
Item2 Item7 Item12
Item3 Item8 Item13
Item4 Item9 Item14
Item5 Item10 Item15
If you're doing this in a table, you'd be going across then down, so you'd need to draw every fifth item before jumping down a row.
$numItems = count($items);
$numRows = 5;
$numColumns = ceil($numItems / $numRows);
echo "<table>";
for ($r = 0; $r < $numRows; ++$r) {
echo "<tr>";
for ($c = 0; $c < $numColumns; ++$c) {
$itemIndex = $c * $numRows + $r; // 0, 5, 10, 1, 6, 11, 2, 7, 12...
echo "<td>";
if (isset($items[$itemIndex])) {
echo $items[$itemIndex];
} else {
echo " ";
}
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
精彩评论