views:

52

answers:

3

Hello! I have the recursion function. There are an hierarchy users structure. I send a user id to my function and it should find all user under this. Function returns an array of all associates users. My task is to find a levels of this users.

For example:

        User1
       /    \
    User2   User3
   /    \    \ 
User4 User5  User6

User1 have level 0. User2, User3 have level 1. User4, User5, User6 have level 2. How can I find this in my recursion? It is my code:

private function getAssociates($userId) {
    global $generation;
    global $usersUnder;
    if (!isset($generation)) {
        $generation = 1;
    }
    $userDb           =  new Lyf_DB_Table('user');
    $associatesSelect =  $userDb->Select();
    $associatesSelect -> from('user', array('id'))->where('enroller_id = ?', $userId);
    $associates       =  $userDb->fetchAll($associatesSelect)->toArray();
    if (!empty($associates)) {
        foreach ($associates as $associate) {
            $usersUnder[$generation] = $associate['id'];
            $this->getAssociates($associate['id']);
        }
    }
    return $usersUnder;
}
+1  A: 

easy but I don't work in zend so I can't tell you code but I can give you description

make function

function getLevel($id,$level=0){
   take from db(higher lever higher_id if exist){
     $level++
     $level = getLevel(higher_id,$level);
   }
   return $level;    
}

and them call

$level = getLevel($id);
jatt
+2  A: 

Add an extra parameter to your getAssociates() function:

private function getAssociates($userID, $level = 0) {

and when you're processing that level of the tree, store the $level with the rest of the user data, then recurse into the function with:

$this->getAssociates($associate['id'], $level + 1);

and when you initially call the function to start this process, pass in 0 for $level, or leave it blank and let PHP assign the default (also 0).

Marc B
+1  A: 

Have a look at iterators:

$user_array= array('1',array(array('2')));
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($user_array));
foreach($it as $user){

     print_r($it->getDepth());
}
Auirio