1
我寫了一個遞歸函數,它通過查看每個員工經理來生成組織圖。該函數的工作原理,但是我有一個返回值的問題。代碼使用了兩個函數,都是遞歸的。他們使用相同的思維構建。PHP遞歸函數返回
我的問題在函數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);
}
}
}
太棒了 - 這個伎倆。我會在代碼中發佈代碼以供其他人使用。 – henrikthorn 2012-01-09 09:36:30