开发者

php recursion level

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)->toA开发者_开发技巧rray();
    if (!empty($associates)) {
        foreach ($associates as $associate) {
            $usersUnder[$generation] = $associate['id'];
            $this->getAssociates($associate['id']);
        }
    }
    return $usersUnder;
}


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).


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());
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜