我有一个名为组织的表 像下面这样
id departmentName parentId
1 ABC Company Ptd Ltd 0
2 IT Department 1
3 Procurement Dept 1
4 Invoicing Team 3
5 Credit Control Team 3
6 Human Resource Dept 1
id 为 1 的行永远不会被删除,并且始终将 0 作为parentId(充当根)
我怎样才能正确地将每个循环与其各自的父级或下级相关联?
我已经这样做了,但还没有成功
$result = mysqli_query($con,"SELECT * FROM organization WHERE id=1");
while($row = mysqli_fetch_array($result))
echo "<ul>";
{
?>
<li><?php echo $row['departmentName'];?><li>
<ul>
<?php
$result2 = mysqli_query($con,"SELECT * FROM organization WHERE parentId=$row[id]");
while($row2 = mysqli_fetch_array($result2))
{
?>
<li><?php echo $row2['departmentName'];?>
<ul>
<li><?php echo $row2['departmentName'];?></li>
<li><?php echo $row2['departmentName'];?></li>
</ul>
</li>
<?php
}
?>
</ul>
<?php
}
?>
这个想法是它必须输出每个的干净无序列表
感谢您的帮助
谢谢
最佳答案
获取值后,您需要先将它们分组,您也可以创建一个递归函数,然后回显列表。考虑这个例子:
$con = new mysqli('localhost', 'username', 'password', 'database');
$result = mysqli_query($con, 'SELECT * FROM `organization`');
$fetched_array = array();
while($row = $result->fetch_assoc()) {
$fetched_array[] = $row;
}
// // nest first the array
function build_array($array, $parentId = 0) {
$values = array();
foreach($array as $value) {
if($value['parentId'] == $parentId) {
$child = build_array($array, $value['id']);
if($child) {
$value['children'] = $child;
}
$values[] = $value;
}
}
return $values;
}
$formatted_values = build_array($fetched_array);
// format them into ul li
function build_list($array) {
$list = '<ul>';
foreach($array as $key => $value) {
foreach($value as $key => $index) {
if(is_array($index)) {
$list .= build_list($index);
} else {
if(!is_numeric($index)) {
$list .= "<li>$index</li>";
}
}
}
}
$list .= '</ul>';
return $list;
}
echo build_list($formatted_values);
应该回显如下内容:
<ul>
<li>ABC Company Ptd Ltd</li>
<li>
<ul>
<li>IT Department</li>
<li>Procurement Dept</li>
<li>
<ul>
<li>Invoicing Team</li>
<li>Credit Control Team</li>
</ul>
</li>
<li>Human Resource Dept</li>
</ul>
</li>
</ul>
关于php - 如何使用css3 UL LI循环并生成分层图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24611063/