Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)->toArray();
    if (!empty($associates)) {
        foreach ($associates as $associate) {
            $usersUnder[$generation] = $associate['id'];
            $this->getAssociates($associate['id']);
        }
    }
    return $usersUnder;
}
like image 758
Alex Pliutau Avatar asked Jun 30 '26 11:06

Alex Pliutau


1 Answers

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

like image 108
Marc B Avatar answered Jul 03 '26 01:07

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!