I can't build a tree of categories.



  • Hey, everybody. There's this structure I have.

    • id is category key
    • parent_id - id parent
    • name of section

    How does it make a tree of categories?



  • $result=mysql_query("SELECT * FROM  categories");
    if   (mysql_num_rows($result) > 0){
        $cats = array();
        while($cat =  mysql_fetch_assoc($result)){
            $cats_ID[$cat['id']][] = $cat;
            $cats[$cat['parent_id']][$cat['id']] =  $cat;
        }
    }
    
    function build_tree($cats,$parent_id,$only_parent = false){
        if(is_array($cats) and isset($cats[$parent_id])){
            $tree = '<ul>';
            if($only_parent==false){
                foreach($cats[$parent_id] as $cat){
                    $tree .= '<li>'.$cat['name'].' #'.$cat['id'];
                    $tree .=  build_tree($cats,$cat['id']);
                    $tree .= '</li>';
                }
            }elseif(is_numeric($only_parent)){
                $cat = $cats[$parent_id][$only_parent];
                $tree .= '<li>'.$cat['name'].' #'.$cat['id'];
                $tree .=  build_tree($cats,$cat['id']);
                $tree .= '</li>';
            }
            $tree .= '</ul>';
        }
        else return null;
        return $tree;
    }
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2