我们可以使用PHP和MySQL来保存员工层次结构数据。在数据库中,我们可以使用一个表来存储员工的信息。该表包含员工的ID、姓名、上级ID和其他相关信息。
下面是示例代码:
创建一个名为“employees”的表:
CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), supervisor_id INT, other_info VARCHAR(255) );
存储员工:
INSERT INTO employees (name, supervisor_id, other_info) VALUES ('John', 0, 'Manager'); INSERT INTO employees (name, supervisor_id, other_info) VALUES ('Jane', 1, 'Assistant Manager'); INSERT INTO employees (name, supervisor_id, other_info) VALUES ('Bob', 2, 'Employee');
查询所有员工:
SELECT * FROM employees ORDER BY supervisor_id;
查询员工的下属:
SELECT * FROM employees WHERE supervisor_id = 1 ORDER BY id;
将所有员工以树形结构显示出来:
function display_employee_hierarchy($parent_id = 0, $spacing = '') { $result = mysqli_query($conn, "SELECT * FROM employees WHERE supervisor_id = $parent_id");
while ($row = mysqli_fetch_array($result)) {
echo $spacing . $row['name'] . "
";
display_employee_hierarchy($row['id'], $spacing . ' ');
}
}
display_employee_hierarchy();
使用上述代码,我们可以保存和查询员工层次结构,以及在页面上以树形结构显示员工。