我编写了一个递归函数,它通过查看每个员工经理来生成组织图。该函数有效,但是我遇到了返回值的问题。代码使用两个函数,它们都是递归的。它们使用相同的思维模式构建。
我的问题在于函数get_top_org,当遇到没有任何员工的第一个员工时,它会突破循环。该功能应该通过映射管理员的所有员工来继续。我可以通过删除递归返回来获得执行此操作的功能(返回get_top_org($ emp-> username,$ organization,$ level,$ limit);)。然后该函数将遍历所有员工,但返回null。
感谢任何帮助!
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);
}
}
}
答案 0 :(得分:0)
您循环遍历员工列表,但随后从该循环中返回。所以你在这里写的功能只会访问一名员工。
不是直接将(递归)调用的结果返回到get_top_org,而是应该结合每个调用的结果并在for循环结束后返回。