PHP递归函数检索类别的所有子项

发布于 2024-09-11 13:28:47 字数 1204 浏览 5 评论 0原文

我想编写一个递归 PHP 函数来检索指定类别的所有子项。我尝试了此处描述的方法,但没有输出我所期望的。

我的类别表如下所示:

CREATE TABLE `categories` (
 `category_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
 `category_name` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_slug` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_parent` smallint(5) unsigned NOT NULL DEFAULT '0',
 `category_description_ro` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_description_en` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1

下面是表中数据的示例:

category id | category name | category_parent

1            Categoria 1            0        
2            Categoria 2            0        
3            Categoria 3            0        
4            Categoria 1.1          1        
5            Categoria 1.2          1        
6            Categoria 1.3          1        
7            Categoria 1.1.2        4 

谢谢。

I would like to write a recursive PHP function to retrive all the children for the specified category. I tried the one described here but it didn't output what I have expected.

My categories table looks like this:

CREATE TABLE `categories` (
 `category_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
 `category_name` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_slug` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_parent` smallint(5) unsigned NOT NULL DEFAULT '0',
 `category_description_ro` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_description_en` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1

Bellow is an example of data in the table:

category id | category name | category_parent

1            Categoria 1            0        
2            Categoria 2            0        
3            Categoria 3            0        
4            Categoria 1.1          1        
5            Categoria 1.2          1        
6            Categoria 1.3          1        
7            Categoria 1.1.2        4 

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

勿忘初心 2024-09-18 13:28:47
function get_categories($parent = 0)
{
    $html = '<ul>';
    $query = mysql_query("SELECT * FROM `categories` WHERE `category_parent` = '$parent'");
    while($row = mysql_fetch_assoc($query))
    {
        $current_id = $row['category_id'];
        $html .= '<li>' . $row['category_name'];
        $has_sub = NULL;
        $has_sub = mysql_num_rows(mysql_query("SELECT COUNT(`category_parent`) FROM `categories` WHERE `category_parent` = '$current_id'"));
        if($has_sub)
        {
            $html .= get_categories($current_id);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}

print get_categories();
function get_categories($parent = 0)
{
    $html = '<ul>';
    $query = mysql_query("SELECT * FROM `categories` WHERE `category_parent` = '$parent'");
    while($row = mysql_fetch_assoc($query))
    {
        $current_id = $row['category_id'];
        $html .= '<li>' . $row['category_name'];
        $has_sub = NULL;
        $has_sub = mysql_num_rows(mysql_query("SELECT COUNT(`category_parent`) FROM `categories` WHERE `category_parent` = '$current_id'"));
        if($has_sub)
        {
            $html .= get_categories($current_id);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}

print get_categories();
旧伤还要旧人安 2024-09-18 13:28:47

我发现了一个非常简单的示例,它适用于从数据库检索的一组类别。查询“SELECT * FROMcategories”将创建所有类别的数组。

在我的类别表中,有字段“id”、“parent_id”和“name”。就这样。
基本类别的父 ID 设置为 0。子类别的 Parent_id 设置为父类别 ID。简单吧?代码如下:

$categories = [

            ['id'=>1,'parentID'=>0, 'name' => 'Main 1' ],
            ['id'=>2,'parentID'=>0, 'name' => 'Main 2' ],
            ['id'=>3,'parentID'=>0, 'name' => 'Main 3' ],
            ['id'=>4,'parentID'=>0, 'name' => 'Main 4' ],
            ['id'=>5,'parentID'=>1, 'name' => 'sub 1 - 1' ],
            ['id'=>6,'parentID'=>1, 'name' => 'sub 1 - 2' ],

            ['id'=>11,'parentID'=>5, 'name' => 'sub 1 - 2' ],
            ['id'=>12,'parentID'=>5, 'name' => 'sub 1 - 2' ],
            ['id'=>13,'parentID'=>5, 'name' => 'sub 1 - 2' ],
            ['id'=>14,'parentID'=>6, 'name' => 'sub 1 - 2' ],


            ['id'=>7,'parentID'=>2, 'name' => 'sub 2 - 1' ],
            ['id'=>8,'parentID'=>2, 'name' => 'sub 2 - 2' ],
            ['id'=>9,'parentID'=>3, 'name' => 'sub 3 - 1' ],
            ['id'=>10,'parentID'=>3, 'name' => 'sub 3 - 2' ]
        ];

        function getCategories($categories, $parent = 0)
        {
            $html = "<ul>";
            foreach($categories as $cat)
            {
                if($cat['parentID'] == $parent)
                {
                    $current_id = $cat['id'];
                    $html .= "<li>" . $cat['name'] ;
                        $html .= getCategories($categories, $current_id);

                    $html .= "</li>";
                }
            }
            $html .= "</ul>";
            return $html;
        }



        echo getCategories($categories) ;

$categories 数组是一个 sql 查询“SELECT * FROMcategories”的效果

I've found quite a simple example that works over an array of categories retrieved from a DB. The query "SELECT * FROM categories" will create an array of all the categories.

In my categories table I have the fields 'id','parent_id'and 'name'. That's all.
Base categories have parent id set as 0. Subcats have parent_id set as parent category ID. Simple right ? Here is the code :

$categories = [

            ['id'=>1,'parentID'=>0, 'name' => 'Main 1' ],
            ['id'=>2,'parentID'=>0, 'name' => 'Main 2' ],
            ['id'=>3,'parentID'=>0, 'name' => 'Main 3' ],
            ['id'=>4,'parentID'=>0, 'name' => 'Main 4' ],
            ['id'=>5,'parentID'=>1, 'name' => 'sub 1 - 1' ],
            ['id'=>6,'parentID'=>1, 'name' => 'sub 1 - 2' ],

            ['id'=>11,'parentID'=>5, 'name' => 'sub 1 - 2' ],
            ['id'=>12,'parentID'=>5, 'name' => 'sub 1 - 2' ],
            ['id'=>13,'parentID'=>5, 'name' => 'sub 1 - 2' ],
            ['id'=>14,'parentID'=>6, 'name' => 'sub 1 - 2' ],


            ['id'=>7,'parentID'=>2, 'name' => 'sub 2 - 1' ],
            ['id'=>8,'parentID'=>2, 'name' => 'sub 2 - 2' ],
            ['id'=>9,'parentID'=>3, 'name' => 'sub 3 - 1' ],
            ['id'=>10,'parentID'=>3, 'name' => 'sub 3 - 2' ]
        ];

        function getCategories($categories, $parent = 0)
        {
            $html = "<ul>";
            foreach($categories as $cat)
            {
                if($cat['parentID'] == $parent)
                {
                    $current_id = $cat['id'];
                    $html .= "<li>" . $cat['name'] ;
                        $html .= getCategories($categories, $current_id);

                    $html .= "</li>";
                }
            }
            $html .= "</ul>";
            return $html;
        }



        echo getCategories($categories) ;

$categories array is an effect of one sql query "SELECT * FROM categories"

各空 2024-09-18 13:28:47

这是我用来显示嵌套链接的东西,它只进行一个数据库查询,然后将结果缓存在一个有用的数组中。

function generate_menu($parent, $menu_array=Array(), $level = 0, $first=0)
    {
        $has_childs = false;

        if (empty($menu_array)) {

            $rs = mysql_query("SELECT id, parent, name FROM cats");

            while ( $row = mysql_fetch_assoc($rs) )
            {
                    $menu_array[$row['id']] = array('name' => $row['name'],'parent' => $row['parent']);
            }        
        }

        foreach ($menu_array as $key => $value)
        {
            if ($value['parent'] == $parent) 
            {   
                //if this is the first child print '<ul>'           
                if ($has_childs === false) {
                        //don't print '<ul>' multiple times             
                        $has_childs = true;
                        if ($first == 0){
                            echo "<ul id=\"nav\">\n";
                            $first = 1;
                        } else {
                            echo "\n<ul>\n";
                        }
                }
                $pad = str_repeat('– ', $level);
                echo "<li><a href=\"http://" . $value['url'].'/\">' . $value['name'] . "</a>";
                generate_menu($key, $menu_array, $level + 1, $first);
                //call function again to generate nested list for subcategories belonging to this category
                echo "</li>\n";
            }
        }
        if ($has_childs === true) echo "</ul>\n";
    }

Here is something I use for displaying nested links, it only makes one DB query then caches the results in a useful array..

function generate_menu($parent, $menu_array=Array(), $level = 0, $first=0)
    {
        $has_childs = false;

        if (empty($menu_array)) {

            $rs = mysql_query("SELECT id, parent, name FROM cats");

            while ( $row = mysql_fetch_assoc($rs) )
            {
                    $menu_array[$row['id']] = array('name' => $row['name'],'parent' => $row['parent']);
            }        
        }

        foreach ($menu_array as $key => $value)
        {
            if ($value['parent'] == $parent) 
            {   
                //if this is the first child print '<ul>'           
                if ($has_childs === false) {
                        //don't print '<ul>' multiple times             
                        $has_childs = true;
                        if ($first == 0){
                            echo "<ul id=\"nav\">\n";
                            $first = 1;
                        } else {
                            echo "\n<ul>\n";
                        }
                }
                $pad = str_repeat('– ', $level);
                echo "<li><a href=\"http://" . $value['url'].'/\">' . $value['name'] . "</a>";
                generate_menu($key, $menu_array, $level + 1, $first);
                //call function again to generate nested list for subcategories belonging to this category
                echo "</li>\n";
            }
        }
        if ($has_childs === true) echo "</ul>\n";
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文