获取所有子类别的递归函数

时间:2010-03-07 23:15:41

标签: php mysql algorithm recursion

以下是我要做的事情: - 我需要一个函数,当作为参数传递时,ID(对于一类事物)将提供所有子类别和子子类别以及sub-sub-sub..etc。 - 我正在考虑使用递归函数,因为我不知道它们的子子类别的子类别的数量等等 所以这就是我到目前为止所做的事情

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,我将得不到相同的结果。我需要一些帮助来解决这个问题或从头开始重写

7 个答案:

答案 0 :(得分:13)

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

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的数组。我希望这有任何帮助。

答案 1 :(得分:5)

database tree to multidimensional array

<?php
function getTree($rootid)
{
   $arr = array();

   $result = mysql_query("select * from PLD_CATEGORY where PARENT_ID='$rootid'");
   while ($row = mysql_fetch_array($result)) { 
     $arr[] = array(
       "Title" => $row["Title"],
       "Children" => getTree($row["id"])
     );
   }
   return $arr;
}
?>

答案 2 :(得分:4)

由于这是由@Pawan Sharma提出的,我认为我也可以给出一些答案。

所有给定的解决方案都存在常见问题 - 它们为每个孩子执行SQL查询。例如,如果第二级有100个孩子,那么将完成100个查询,而实际上可以使用where parent_id in (<list_of_ids>)单个查询中完成。


示例DB:

create table category (
    id          int auto_increment primary key,
    parent_id   int default null,
    title       tinytext,
    foreign key (parent_id) references category (id)
) engine = InnoDB;

insert into category (id, parent_id, title) values
    (1, null, '1'),
    (2, null, '2'),
    (3, null, '3'),
    (4, 1   , '1.1'),
    (5, 1   , '1.2'),
    (6, 1   , '1.3'),
    (7, 4   , '1.1.1'),
    (8, 4   , '1.1.2'),
    (9, 7   , '1.1.1.1');

这是我的解决方案:

/**
 * @param null|int|array $parentID
 */
function getTree($parentID) {
    $sql = "select id, parent_id, title from category where ";
    if ( is_null($parentID) ) {
        $sql .= "parent_id is null";
    }
    elseif ( is_array($parentID) ) {
        $parentID = implode(',', $parentID);
        $sql .= "parent_id in ({$parentID})";
    }
    else {
        $sql .= "parent_id = {$parentID}";
    }

    $tree = array();
    $idList = array();

    $res = mysql_query($sql);
    while ( $row = mysql_fetch_assoc($res) ) {
        $row['children'] = array();
        $tree[$row['id']] = $row;
        $idList[] = $row['id'];
    }
    mysql_free_result($res);

    if ( $idList ) {
        $children = getTree($idList);
        foreach ( $children as $child ) {
            $tree[$child['parent_id']]['children'][] = $child;
        }
    }
    return $tree;
}

使用提供的示例数据,当调用getTree(null)时(对于所有条目),它最多可执行5次查询:

select id, parent_id, title from category where parent_id is null
select id, parent_id, title from category where parent_id in (1,2,3)
select id, parent_id, title from category where parent_id in (4,5,6)
select id, parent_id, title from category where parent_id in (7,8)
select id, parent_id, title from category where parent_id in (9)

当调用getTree(4)时,会执行3个查询:

select id, parent_id, title from category where parent_id = 4
select id, parent_id, title from category where parent_id in (7,8)
select id, parent_id, title from category where parent_id in (9)

答案 3 :(得分:1)

function categoryChild($id)
{
    $s = "SELECT category_id,name FROM proads_categories 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['category_id']]['nam'] = $row['name'];
            $arr = categoryChild($row['category_id']);
            if(count($arr) > 0)
            {
                $children[$row['category_id']]['child'] = categoryChild($row['category_id']);
            } 
        }
    }
    return $children;
}

这很完美。如果您需要,请试试这个

答案 4 :(得分:1)

function breadCrumb($id)
{
    $ar = array();
    $result = mysql_query("SELECT * FROM groups WHERE ParentID = '$id'");
    if(mysql_num_rows($result) > 0)
    {
        while($row = mysql_fetch_object($result))
        {
            $ar[] = $row->DBGroupID;
            $r = mysql_query("SELECT * FROM groups WHERE ParentID = '".$row->GroupID."'");
            if(mysql_num_rows($r) > 0)
                $ar = array_merge($ar, breadCrumb($row->GroupID, 1));
        }
    }
    return $ar;
}

答案 5 :(得分:1)

<?php    
require('db/dbconnect.php');   

$user_id='triD-100';   
 $sql="select * from ajent_joining where sponser_id='".$user_id."'";   
 $qR=mysql_query($sql);   
 while($rowD=mysql_fetch_assoc($qR)){    
  echo $childId=$rowD["user_id"]; 
    echo "<br/>";  
  categoryChild($childId);    
   }   

  function categoryChild($childId) {   

    $s = "select user_id from ajent_joining where sponser_id='".$childId."'";
    $r = mysql_query($s);
    if(mysql_num_rows($r) > 0) {

       while($row = mysql_fetch_array($r)) {

          echo $childId=$row["user_id"];
          echo "<br/>";   
           categoryChild($childId);
    }
}

}


?>

答案 6 :(得分:0)

使用Prestashop功能:

public function getRecursiveChildren() {

    $subCategories = $this->recurseLiteCategTree();
    //print_r($subCategories);


    $my_tab = array();

    foreach ($subCategories['children'] as $subc) {
        $my_tab[]   = $subc['id'];
        foreach ($subc['children'] as $subc2) {
            $my_tab[]   = $subc2['id'];
            foreach ($subc2['children'] as $subc3) {
                $my_tab[]   = $subc3['id'];
                foreach ($subc3['children'] as $subc4) {
                    $my_tab[]   = $subc4['id'];
                }
            }
        }
    }
    $my_tab [] = $this->id; 

    return $my_tab;
}

这可以通过使用递归来改善,但今天没有时间:'(