Divide rows from db against fixed <li> columns in PHP
I did a search, but nothing I saw was the same or could help.
I've got rows coming in from a db and what I want to do is divide that into 5 columns.
This is what I have, it only shows 4 columns and well I'm stuck....
$result
is the array containing the db rows.
$divider = floor(count($result) / 5);
$roundup = ceil(count($result) / 5);
$start = 0;
for ($i = 0; $i <= $divider; $i++) {
$splResult = array_slice($result, $start, $roundup);
$content .= '<li>';
foreach ($splResult as $row) {
$content = "content goes here";
}
$content .= '</li>';
$start = $start + $roundup;
}
So lets say I have 16 items coming in. The result I would like to get is (or at least better distributed):
<ol>
<li>
<div>1</div>
<div>2</div>
<div>3</div>
</li>
<li>
<div>4</div>
<div>5</div>
<div>6</div>
</li>
<li>
<div>7</div>
<div>8</div>
<div>9</div>
</li>
<li>
<div>10</div>
<div>11</div>
开发者_开发百科 <div>12</div>
</li>
<li>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
</li>
</ol>
Note: what comes in from the db could range from 0 to 100 rows. But it must always be divided in 5 columns.
Here's a solution. No guarantees that it's the best.
$cnt = count($result);
// creates an array which evenly distributes numbers across
// a series of entries.
$nums = array(0,0,0,0,0);
for( $i = 0; $i < $cnt; $i++ ) $nums[ $i % 5 ]++;
echo '<ol>';
$k = 0;
for( $i = 0; $i < 5; $i++ )
{
echo '<li>';
// iterate through the count for this column.
for( $j = 0; $j < $nums[ $i ]; $j++ )
{
echo '<div>' . $result[ $k ] . '<div>';
$k++;
}
echo '</li>';
}
echo '</ol>';
精彩评论