Zend - The PHP Company




Menus & Navigation

Add Code


Tree of categories  

Type: code fragment
Added by: atur
Entered: 07/06/2003
Last modified: 06/12/2002
Rating: **** (3 votes)
Views: 7091
This code print out an hierarchical categories tree structure with indents of the kind ID, ID_PARENT, TITLE.


<?php

 
// Recusive tree function
 //
 
function tree($id_parent 0$indent 0)
    {
        global 
$g_tree$ret_tree;
        
$tt = array();
        
$x 0;
        
$loop 0;

        foreach(
$g_tree as $n)
        {         
            if( 
$n['id_parent'] == $id_parent)
            {
                
$tt[$x++] = $loop;  
            }  
            
$loop++;
        }
        
/*-- if there are some parent ids --*/
        
if( $x != 0){             
            foreach(
$tt as $d)
            {
                
$tmp = array();
                
                foreach(
$g_tree[$d] as $key => $value)
                {                
                    
$tmp[$key] = $value
                }
                
$tmp['indent'] = $indent;

                
$ret_tree[] = $tmp;
                
                
tree($tmp['id'], $indent+1);
            }
        }
        else
        {
            return;
        }
    }

// Example of how to use it
//

// This is your tree structure. It should be sorted by titles
//
$g_tree = array();
 
$g_tree[]  = array(
                    
'id'        => 1,
                    
'id_parent' => 0,
                    
'title'     => 'Astronomy'
);   
$g_tree[]  = array(
                    
'id'        => 2,
                    
'id_parent' => 1,
                    
'title'     => 'Radio-Astronomy'
); 
$g_tree[]  = array(
                    
'id'        => 3,
                    
'id_parent' => 2,
                    
'title'     => 'Radio-Observatories'
);   
$g_tree[]  = array(
                    
'id'        => 4,
                    
'id_parent' => 0,
                    
'title'     => 'Physics'
);  
$g_tree[]  = array(
                    
'id'        => 5,
                    
'id_parent' => 4,
                    
'title'     => 'Lasers'
);
$g_tree[]  = array(
                    
'id'        => 6,
                    
'id_parent' => 4,
                    
'title'     => 'Photonics'
);
  
  
// This the the return array with indents
//
$ret_tree = array();
 
// __Recursive function call__
// If you want to print out only
// a subtree you have to modify the first value
// of this function to the id of the subtree
//
tree(0,0);
 
//Print the tree structure with indents
//
foreach($ret_tree as $cat)
{
    
$indent '';
    
    for(
$i=0;$i<$cat['indent'];$i++)
    {
        
$indent .= '___';
    }
  
    echo 
$indent.$cat['title'].'<br>';
}

?>


Usage Example




Rate This Script





Search



This Category All Categories