PHP Recursive Function

Posted by Tempname on Stack Overflow See other posts from Stack Overflow or by Tempname
Published on 2010-06-07T08:39:35Z Indexed on 2010/06/07 8:42 UTC
Read the original article Hit count: 227

Filed under:
|

In my database I have a hierarchical flat table that returns data ordered by ParentID, ObjectID asc

I am having a bit of an issue getting this recursive function to work properly. I get the first Parent>Child>Child but after that I get nothing else.

Any help with this is greatly appreciated.

Here is my testing code:

$objectArr = array();

$objectData = DAOFactory::getTemplateObjectsDAO()->queryByTemplateID(1);

for($i = 0; $i < count($objectData); $i++)
{
    if(empty($objectData[$i]->parentID))
    {
        echo $objectData[$i]->objectID;
        $objectArr[$i] = $objectData[$i];
        $objectArr[$i]->children = array();
        $objectArr[$i]->children = getChildren($objectData[$i]->objectID, $objectData);
    }
}

function getChildren($objectID, $data)
{
    $childArr = array();
    foreach($data as $object)
    {
        if($object->parentID == $objectID)
        {
            $childArr = $object;
            $childArr->children = array();
            $childArr->children = getChildren($object->objectID, $data);
        }
    }
    return $childArr;
}

new dBug($objectData);

This is the output that I am getting:

Fullsize Link

alt text

© Stack Overflow or respective owner

Related posts about php

Related posts about recursion