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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.