How to display categories in an unordered list
I need help to display a list of entries in an unordered list from a database. The problem I have now is how to loop through the array of data coming from the database to display in groups of say tens.
So the first ten categories will display in the first . And subsequent categories also displayed in their respective s.
Eg.
<ul>
<li>Category 1 Item 1</li>
<li>Category 1 Item 1</li>
... ......................... . .......
<li>Category 1 Item 10</li>
</ul>
<ul>
<li>Category 2 Item 1</li>
<li>Category 2 Item 1</li>
... .....................开发者_开发技巧.... . .......
<li>Category 2 Item 10</li>
</ul>
Any help will greatly be appreciated. Thanks
echo("<ul>");
$count = 0;
while(...fetch next row...) {
if($count % 10 == 0)
echo("</ul><ul>");
echo("<li>" . $catName . "</li>");
$count++;
}
echo("</ul>");
The problem I have now is how to loop through the array of data coming from the database to display in groups of say tens.
How are your categories organized in your row? I'm going to assume you have a single "category" column that you're trying to organize by. AND that you've sorted it in the query by using ORDER BY.
Then assuming you have an array of these sorted rows, you can just track when the category changes
$currCat = "NotaNumber";
$output = "";
while ($row = mysql_fetch_row($queryRes))
{
# when the category changes, add closing and opening ul's
# we'll trim the excess </ul> and <ul> off later
# You can change this to also limit the number printed
# by combining with the other answer
if ($row['categoryColumn'] != $currCat)
{
$output .= "</ul>";
$output .= "<ul>";
$currCat = $row['categoryColumn'];
}
$output .= "<li> Category No: " . $row['categoryColumn'] .
" Data:" . $row['catData'] . "</li>";
}
# Trim </ul> from front and <ul> from back by getting a substring
$output = substr($output, 5, strlen($output) - 9);
echo $output
Original answer
Printing categories organized as array of arrays:
function printCategories($catItems)
{
echo "<ul>";
$numPrinted = 0;
foreach ($catItems as $catItem)
{
echo "<li> $catEntry </li>"
$numPrinted++;
if ($numPrinted > 10)
{
break;
}
}
echo "</ul>";
}
foreach ($categories as $category)
{
printCategories($category);
}
There's a lot of PHP tags in there, but I'm assuming you'll use this in your view so you're going to have HTML to fill it out in any case.
<?php $i = 0; ?>
<?php foreach($categories as $catgory) : ?>
<?php if ($i == 0) : ?>
<ul>
<?php endif; ?>
<li>$catgory</li>
<?php if ($i == 9) : $i = 0 ?>
</ul>
<?php endif; ?>
<?php $i++; ?>
<?php endforeach ?>
Use PHPTAL
$categories = array_chunk($categories, 10);
$tal = new PHPTAL;
$tal->categories = $categories;
$html = <<<HTML
<ul tal:repeat="category categories">
<li tal:repeat="item category">
Category ${repeat/category/number}
Item ${repeat/item/number}
</li>
</ul>
HTML;
$tal->setSource($html, __FILE__);
echo $tal->execute();
精彩评论