I’ve written a recursive function, which generates an organizational diagram by looking at each employees manager. The function works, however I have an issue with values being returned. The code uses two functions, which are both recursive. They are build using the same mindset.
My problem lies within function get_top_org, which breaks out of the loop when getting to the first employee, who do not have any employees. The function should continue by mapping all employees for the manager. I can get the function to do this by removing the recursive return (return get_top_org($emp->username, $organisation, $level, $limit);). Then the function will go through all the employees, but returns null.
Any help is appreciated!
function get_top_managers($username, $account, $layer, $managers){
global $DB;
$manager = $DB->get_record('user_info_data', array('fieldid' => 2, 'userid' => (String)$account->id));
if($manager->data != ""){
$managers[$username][] = $manager->data;
$manager_account = $DB->get_record('user', array('username' => (String)$manager->data));
return get_top_managers($username, $manager_account, $layer + 1, $managers);
}else{
return $managers;
}
}
function get_top_org($username, $organisation, $level, $limit){
global $DB;
$employees = $DB->get_records_select('user_info_data', "fieldid = 2 AND data LIKE '$username'");
if(count($employees) != 0){
foreach($employees as $emp){
if($emp = $DB->get_record('user', array('id' => $emp->userid))){
$managers = array();
$last = "";
$managers = get_top_managers($emp->username, $emp, 0, $managers);
$managers = $managers[$emp->username];
foreach($managers as $manager){
$merger = array();
if($last != ""){
$merger[$manager] = $last;
$last = $merger;
}
}
$organisation = array_merge_recursive($organisation, $merger);
//This return statement gets the function to stop running, however - if removed the function returns null but runs as it should.
return get_top_org($emp->username, $organisation, $level, $limit);
}
}
}else{
if($non_manager = $DB->get_record('user', array('username' => $username))){
$managers = array();
$last = "";
$managers = get_top_managers($non_manager->username, $non_manager, 0, $managers);
$managers = $managers[$non_manager->username];
foreach($managers as $manager){
$merger = array();
if($last != ""){
$merger[$manager] = $last;
$last = $merger;
}else{
$last = array($manager => $non_manager->username);
}
}
return array_merge_recursive($organisation, $merger);
}
}
}
You’re looping over a list of employees, but then returning from within that loop. So the function as you have written it here will only visit one employee.
Instead of returning the results of your (recursive) call to get_top_org directly, you should combine the results of each call and return that after the for loop has finished.