我有员工表,有些员工是经理。 我需要一个带有员工ID的函数,并创建一个包含向其报告的所有员工的多维数组。到目前为止,我能够打印树:
function drillDownStaff($emplid){
$conn = db_connect();
$sql = "SELECT
employees.EmployeeID, employees.ManagerID
FROM
employees
WHERE
employees.ManagerID = '".$emplid."';
$result = mysql_query($sql,$conn);
while($row = mysql_fetch_assoc($result)){
echo "<ul>";
echo "<li>".$row['FullName'];
drillDownStaff($row['EmployeeID']);
echo "</li>";
echo "</ul>";
}
}
这将打印出一个不错的经理 - &gt;员工树:
但我喜欢的是使用员工树返回多维数组的递归函数,如下所示:
array(
[5] => array(
[FullName] => John
[...] => Other emp details
[manages] => array(
[6]=>array(
[FullName]=>Jane
[...]=>other emp details
[manages]=> array(Pauls' details)
)
[7]=>array(...) // emp details again
)
)
)
这可能吗?
答案 0 :(得分:1)
构建人员树的递归函数如下。请记住,这不是很有效,所以如果你有一个有数百/数千名工作人员的树,不要指望它特别高效。
function buildStaffTree($managerId = null) {
global $staff;
$subordinates = array_values(array_filter(
$staff,
function ($staffMember) use ($managerId) {
return $staffMember['manager'] === $managerId;
}
));
if ($managerId === null) {
// Tree root - only enumerate the top-level managers
return array_map(
function ($subordinate) {
return buildStaffTree($subordinate['id']);
},
$subordinates
);
} else {
$manager = array_values(array_filter(
$staff,
function ($staffMember) use ($managerId) {
return $staffMember['id'] === $managerId;
}
))[0];
return [
'id' => $manager['id'],
'name' => $manager['name'],
'manages' => array_map(
function ($subordinate) {
return buildStaffTree($subordinate['id']);
},
$subordinates
)
];
}
}
此代码运行的示例是available here。