Need Some Advice With Php Loop
I need to make a loop that get data from the db...and print the data in BUT every 5 li need to be in a ul... how can I do this loop?
Solution 1:
You can do that with NoRewindIterator
and with LimitIterator
. Just wrap the Iterator you get back from your database client library that represents the resultset into the NoRewindIterator
and you then can do the 5 iterations each with the LimitIterator
until the overall iterator is invalid:
$it = newNoRewindIterator($result);
$it->getInnerIterator()->rewind(); # Rewind oncewhile ($it->valid())
{
echo'<ul>';
foreach (newLimitIterator($it, 0, 5) as$row)
{
echo'<li>', .... , '</li>' ;
}
echo'</ul>';
}
Edit: Added the rewind()
operation because it is needed by default for some iterators that do not automatically rewind, for all the details see a reference question I've created: When does the NoRewindIterator rewind the inner Iterator?
Solution 2:
Why not use the modulo
operator?
$counter = 0;
echo'<ul>';
while ($row = fetchRow())
{
$counter++;
if ($counter % 5 == 0) echo'</ul><ul>';
echo'<li>' . $row['field'] . '</li>';
}
echo'</ul>';
Solution 3:
Use another counter:
$counter=0;
echo'<ul>';
while($record_in_database=fetch_it_somehow){
if($counter==5){
$counter=0;
echo'</ul><ul>'; // *
}
echo'<li>'.$record_in_database->retrieve_data_somehow().'</li>';
++$counter;
} // end whileecho'</ul>'; // you must close it as you've opened in * marked line
Post a Comment for "Need Some Advice With Php Loop"