如何显示类别和列表

时间:2016-03-03 03:19:52

标签: php mysql

我是php和mysql的新手。我想显示类别和它的列表。我希望它像这样发生。请帮我。我真的很坚持。

我的数据库表:

enter image description here

现在如何:

enter image description here

我需要它

    • 数学
    • 物理
  • 小工具
    • 手机
    • 笔记本
    • 移动电源

我的代码:

$getitems = mysql_query("SELECT category, 
                                name 
                           FROM items_for_checking 
                          WHERE status = 'approved' ");
$numrows = mysql_num_rows($getitems);

if($numrows > 0){
    $row       = mysql_fetch_assoc($getitems);
    $category  = $row['category'];
    $name       = $row['name'];
    $last       = $category;

    echo "<div class='cat'>
              <div class='cat-head'>
                 CATEGORY
              </div>
              <div class='main-cat'>
                  <li>$category<li>
                  <ul>
              </div>
              </div>
          </div>";

while($row = mysql_fetch_assoc($getitems)){
    $category    = $row['category'];
    $name        = $row['name'];

    if($last != $category){
        echo "</ul><li>$category</li><ul>";
    }
    echo "<li>$name</li>";
    $last = $category;
}
echo "</ul>";
}

1 个答案:

答案 0 :(得分:0)

获取数组的唯一类别列表,就像这样

  $row       = mysql_fetch_assoc($getitems);
  $uniqueCategory  = array_unique($row['category']);
  $uniqueCategoryCount=count($uniqueCategory);

for($i=0;$i< $uniqueCategoryCount;$i++)
{
    echo "</ul><li>$uniqueCategory[$i]</li><ul>";
    while($row = mysql_fetch_assoc($getitems)){
    $category    = $row['category'];
    $name        = $row['name'];
    if($uniqueCategory[i]==$row['category']){
    echo "<li>$name</li>";
    }
    }

}