【问题标题】:recursive function to get all the child categories获取所有子类别的递归函数
【发布时间】:2011-01-24 19:10:58
【问题描述】:

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

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

【问题讨论】:

    标签: php mysql algorithm recursion


    【解决方案1】:

    我很难弄清楚你的功能。我认为这会做你想要的。它获取 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 的数组。我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      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;
      }
      ?>
      

      【讨论】:

        【解决方案3】:

        @Pawan Sharma 提出了这个问题,我想我也可以给出一些答案。

        所有给定的解决方案都存在共同问题——它们对每个孩子执行 SQL 查询。例如,如果第 2 级有 100 个孩子,那么将完成 100 个查询,而实际上可以在 single 查询中使用where parent_id in (&lt;list_of_ids&gt;) 完成。


        示例数据库:

        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)
        

        【讨论】:

        • 当您使用那些类似 ip 的标题时,您为什么要这样做,您可以简单地使用带有 like 的 where 语句并获得结果。
        【解决方案4】:
        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;
        }
        

        完美。有需要的可以试试这个

        【讨论】:

          【解决方案5】:
          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;
          }
          

          【讨论】:

            【解决方案6】:
            <?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);
                }
            }
            
            }
            
            
            ?>
            

            【讨论】:

              【解决方案7】:

              使用 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;
              }
              

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

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2017-09-19
                • 1970-01-01
                • 2018-03-30
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多