我有两个表报告,employee_details 报告包含主管_id、下属_id 字段,这些字段是员工详细信息表中的 emp_id。报告表包含三个级别(主管->下属->下属->员工),我想通过从员工详细信息表中获取姓名(作为层次结构)将此数据显示为下拉列表。所以请帮助我有什么办法吗?
最佳答案
如果你想显示它,你肯定需要以数组的形式获取洞树。这有点棘手。
我认为您并不确定树中有多少层。 所以最简单的方法如下,但在大树中它的性能很差。当树长得很大时,你需要检查其他技术。
以下内容是快速编写的,未经测试,可能存在一些错误。但我发布它是为了向您展示一个可能的解决方案:
<?php
class tree {
private $level = 0;
public function getChildsRecoursive($parentid=0,$recoursive=false) {
// you would have your own db object... please replace this...
$db->select("select * from reporting r JOIN employee_details d ON(r.subordinate_id=d.emp_id) where supervisor_id='$parentid' ORDER BY d.name");
$r = array();
while($data = $db->fetchArray()) {
$sid = $data['supervisor_id'];
$cid = $data['subordinate_id'];
if($recoursive) {
$this->level++;
$data['level'] = $this->level;
$data['childs'] = $this->getChildsRecoursive($cid, true);
$this->level--;
}
$r[] = $data;
}
return $r;
}
public function getDropdown() {
// I suspect the top Level have a supervisor_id = 0
$data = $this->getChildsRecoursive(0,true);
// you can do a print_r($data) here to see if the results are correct
$r = "<select>";
foreach($data as $d) {
$r .= $this->getOptionsRecoursive($d);
}
$r .= "</select>";
return $r;
}
public function getOptionsRecoursive($data) {
$r = "<option>";
for($i=0;$i<$data['level'];$i++) {
$r .= " ";
}
$r .= $data['name'];
$r .= "</option>\n";
if(isset($data['childs'])) {
foreach($data['childs'] as $c) {
$r .= $this->getOptionsRecoursive($c);
}
}
return $r;
}
}
?>
希望有助于理解。 (请注意,这会导致许多查询,具体取决于您的树有多大)。
要开始,您需要执行以下操作
$tree = new tree();
echo $tree->getDropdown();
关于php - 用于报告层次结构数据的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16783975/