如何在无序列表中显示类别

时间:2011-04-26 15:51:46

标签: php mysql

我需要帮助才能在数据库的无序列表中显示条目列表。我现在遇到的问题是如何遍历来自数据库的数据数组,以数十组的形式显示。

所以前十个类别将显示在第一个类别中。 后续类别也显示在各自的s中。

例如

<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>

任何帮助将不胜感激。感谢

4 个答案:

答案 0 :(得分:1)

  

我现在遇到的问题是如何循环   通过来自的数据阵列   数据库以组的形式显示   说几十。

您的类别如何组织在您的行中?我假设你有一个单独的“类别”专栏,你正试图组织。并且您已使用ORDER BY在查询中对其进行了排序。

然后假设您有这些已排序行的数组,您只需跟踪类别更改的时间

$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

原始回答

打印按阵列数组织的类别:

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);
}

答案 1 :(得分:1)

echo("<ul>");
$count = 0;
while(...fetch next row...) {
    if($count % 10 == 0)
        echo("</ul><ul>");
    echo("<li>" . $catName . "</li>");
    $count++;
}

echo("</ul>");

答案 2 :(得分:0)

那里有很多PHP标签,但我假设你将在你的视图中使用它,所以你将在任何情况下使用HTML来填充它。

<?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 ?>

答案 3 :(得分:0)

使用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();