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;
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With