Jump to content

Recursion


Skepsis

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/148717-recursion/
Share on other sites

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"

Link to comment
https://forums.phpfreaks.com/topic/148717-recursion/#findComment-780947
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.