Skepsis Posted March 10, 2009 Share Posted March 10, 2009 Well, i have been trying to create a category system, that displays all root categories, and then all sub categories into a nest, i got that part down. now what i want to do is display ALL main categories, then underneath i want to display just the child category, not the child's child category. like say i have, -dad --son ---grandson -mom --daughter ---granddaughter i only want to display the children, not the grandchildren. this is the function i use to call the nest: <?php function generate_tree($g_tree, $parent = 0, $indent = 0) { global $output_tree; $tids = array(); $xid = 0; $loop = 0; foreach($g_tree as $cat) { if($cat['parent'] == $parent) $tids[$xid++] = $loop; $loop++; } if($xid != 0) { foreach($tids as $tid) { $tmp = array(); foreach($g_tree[$tid] as $key => $value) $tmp[$key] = $value; $tmp['indent'] = $indent; $output_tree[] = $tmp; $this->generate_tree($g_tree, $tmp['id'], $indent + 1); } } else return; return $output_tree; } $g_tree = $db->getTable("SELECT id, parent, name FROM parents"); $output_tree = $std->generate_tree($g_tree, 0, 0); foreach($output_tree as $tree) { $name = $tree['name']; $id = $tree['id']; $listTree .= str_repeat("----", $tree['indent']).'<a href=?cid='.$id.'>'.$name.'</a><br>'; } echo $listTree.'<br><br><br>'; ?> Quote Link to comment Share on other sites More sharing options...
btherl Posted March 10, 2009 Share Posted March 10, 2009 A simple way to limit recursion is to add an extra argument "depth". That records what depth you are down to in the recursion. Each time you make a recursive call you increase it by 1. Then to cut off the recursion after 2 levels you just say "if ($depth < 2) do recursive call" Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.