我需要创建一个从数据库获取数据的循环......并打印数据,<li>但每 5 个li需要在一个ul......
我该怎么做这个循环?
你可以用NoRewindIterator和来做到这一点LimitIterator。只需将从表示结果集的数据库客户端库返回的迭代器包装到 中NoRewindIterator,然后您可以使用 5 次迭代,LimitIterator直到整个迭代器无效:
$it = new NoRewindIterator($result);
$it->getInnerIterator()->rewind(); # Rewind once
while ($it->valid())
{
echo '<ul>';
foreach (new LimitIterator($it, 0, 5) as $row)
{
echo '<li>', .... , '</li>' ;
}
echo '</ul>';
}
编辑:添加了该rewind()操作,因为默认情况下某些不自动倒带的迭代器需要它,有关所有详细信息,请参阅我创建的参考问题:NoRewindIterator 何时倒带内部迭代器?
为什么不使用modulo运算符?
$counter = 0;
echo '<ul>';
while ($row = fetchRow())
{
$counter++;
if ($counter % 5 == 0) echo '</ul><ul>';
echo '<li>' . $row['field'] . '</li>';
}
echo '</ul>';
使用另一个计数器:
$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 while
echo '</ul>'; // you must close it as you've opened in * marked line