递归函数来获取所有子类别 [英] recursive function to get all the child categories

查看:36
本文介绍了递归函数来获取所有子类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的:- 我需要一个函数,当作为参数传递时,ID(用于事物类别)将提供所有子类别和子子类别以及子子子子......等.- 我正在考虑使用递归函数,因为我不知道他们的子类别等子类别的数量所以这是我迄今为止尝试做的

Here is what I'm trying to do: - i need a function that when passed as an argument an ID (for a category of things) will provide all the subcategories and the sub-sub categories and sub-sub-sub..etc. - i was thinking to use a recursive function since i don't know the number of subcategories their sub-subcategories and so on so here is what i've tried to do so far

function categoryChild($id) {

    $s = "SELECT * FROM PLD_CATEGORY WHERE PARENT_ID = $id";
    $r = mysql_query($s);

    if(mysql_num_rows($r) > 0) {

        while($row = mysql_fetch_array($r))
            echo $row['ID'].",".categoryChild($row['ID']);
    }
    else {
        $row = mysql_fetch_array($r);
        return $row['ID'];
    }
}

如果我使用 return 而不是 echo,我不会得到相同的结果.我需要一些帮助来解决这个问题或从头开始重写它

If i use return instead of echo, i won't get the same result. I need some help in order to fix this or rewrite it from scratch

推荐答案

我很难弄清楚你的功能.我认为这会做你想做的.它获取 ID 为 $id 的类别的所有子项,以及它们的子项(从而获得您想要的整个子类别、子子类别效果).

I had a hard time trying to figure out your function. I think this will do what you want. It gets all the children of a category with ID $id, and also their children (thus getting the whole sub category, sub sub category effect that you wanted).

function categoryChild($id) {
    $s = "SELECT ID FROM PLD_CATEGORY WHERE PARENT_ID = $id";
    $r = mysql_query($s);

    $children = array();

    if(mysql_num_rows($r) > 0) {
        # It has children, let's get them.
        while($row = mysql_fetch_array($r)) {
            # Add the child to the list of children, and get its subchildren
            $children[$row['ID']] = categoryChild($row['ID']);
        }
    }

    return $children;
}

这个函数会返回:

$var = array(
        'categoryChild ID' => array(
                'subcategoryChild ID' => array(
                        'subcategoryChild child 1' => array(),
                        'subcategoryChild child 2' => array()
                )
        ),
        'anotherCategoryChild ID' => array() # This child has no children of its own
);

它基本上返回一个包含子代 ID 的数组和一个包含其子代 ID 的数组.我希望这对您有所帮助.

It basically returns an array with the ID of the child and an array containing the IDs of its children. I hope this is of any help.

这篇关于递归函数来获取所有子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆