R
R
Ruslan Polin2016-09-07 02:08:20
PHP
Ruslan Polin, 2016-09-07 02:08:20

How to recursively count the number of subcategories and output the value?

I am building a tree of categories and the task arose to display not only the subcategories themselves, but also their number, but I can’t figure out how to do this.
The penetration depth is not known in advance. Actually here is the code for clarity. From the base we pull out 3 values ​​id, name, cat_id, where cat_id is the id of the parent.

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;
}
if   (mysql_num_rows($result12) > 0){
    $cats = array();
    while($cat =  mysql_fetch_assoc($result12)){
        $cats_ID[$cat['id']][] = $cat;
        $cats[$cat['cat_id']][$cat['id']] =  $cat;
    
    }
}
echo build_tree($cats, 0);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2016-09-07
@Veleses

use static variable like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question