Search code examples
phpalgorithmtraversal

Traversing an Unknown Level of Users for an Organizational Chart


I'm working on an organizational chart in PHP, and the data is retrieved from a database.

An example of the organizational chart looks like the following, but it has an unknown number of levels:

Me

  1. Brandon

  2. David

    a. Amanda

    b. Michelle

    c. Michael

  3. Robert

    a. Kristen

    • Charles

    • Ashley

Traversal-type algorithms has often been my weakness, and I need your help. I have experimented with many variations of a "traverse" function that would call itself, but I just haven't yet arrived at the proper solution.

The temporary solution I have right now is only three levels deep, and you can see why it's not realistic.

foreach($user->getChildren() as $child) {
    echo $child->name;

    foreach($child->getChildren() as $ch) {
        echo $ch->name;

        foreach($ch->getChildren() as $c) {
            echo $c->name;
            // ... more foreach statements
        }
    }
}

$user is of class User, and $user->getChildren() contains an array of User objects that have $user as their parent


Solution

  • Your traverse function could look something like:

    function traverse($users)
    {
        if(empty($users)) return;
    
        foreach($users as $user)
        {
            echo $user->name;
            traverse($user->getChildren());
        }
    }
    

    So you have the stop condition which can be if(empty($users)) return; or if(count($users) == 0) return;, you get the idea, and the foreach loop on each level, which prints the name of the user, and calls the function again for the user's children.

    You would call it as traverse([$user]); where $user is the user you want to start from.