2

我在 php 和 mysql 中工作,我有一个表格类别,我需要在父类别下显示子类别。喜欢

猫1

  -> Subcat1

         -> Subcat11

  -> Subcat2

         --> Subcat21

              --> Subcat211

猫2

  -> Subcat2

         -> Subcat21

              -->Subcat22
  -> Subcat3

         --> Subcat31

              --> Subcat311  

我的表结构是这样的:

CREATE TABLE IF NOT EXISTS `category` (
  `cat_id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'This is primary key of the table',
  `name` varchar(255) DEFAULT NULL,
  `parent_cat_id` bigint(11) NOT NULL,   
  PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ; 

你能帮我吗,如何执行我的查询。

4

3 回答 3

1

例子:

<?php
class RightMenu {
    public $menu;
    public $patch = '';

    public function getMenu($parent = 0) {
        $DB = new DataBase();
        $result = $DB->exec("SELECT * FROM cont_sections WHERE parentid = $parent AND status = 1 ORDER BY name;");
        if(mysql_num_rows($result) > 0) {
            echo '<ul>';
            while($row = mysql_fetch_assoc($result)) {
                if($row['parentid'] == 0){
                    $this->patch = '';
                }
                $this->patch .= '/' . $row["translit"];
                echo '<li><a href="/section'.$this->patch.'.html">' . $row["name"] . '</a>';
                echo $this->getMenu($row["id"]);
                echo '</li>';
            }
            echo '</ul>';
        }
        mysql_free_result($result);
        unset($DB);
    }
}
?>
于 2012-10-15T10:54:24.403 回答
0

您需要编写一个递归函数来显示类别和子猫

getAllSubCats(0);

function getAllSubCats($cat, $depth = NULL)
{
    $this_cat = mysql_fetch_object(mysql_query("select * from categories where id= '$cat'"));

    $indent = str_repeat("     ", $depth);
    echo $indent . $this_cat->name . "<br />";

    $result = mysql_query("select * from categories where parent_cat_id = '$cat'");

    while($cat = mysql_fetch_object($result))
    {
        getAllSubCats($cat->id, $depth + 1);
    }
}

或使用以下查询如果是一二一关系

SELECT cat_id, name, (SELECT name FROM categories WHERE cat_id = a.parent_id) parent_name FROM categories a 
于 2012-10-15T10:46:08.447 回答
0

使用自联接

SELECT p.cat_id, p.name, c.cat_id, c.name
FROM tbl_category p
INNER JOIN tbl_category c ON p.cat_id = c.parent_cat_id

然后用 PHP 操作生成的数组以表格形式显示

于 2012-10-15T10:54:06.777 回答