如何使用css3 UL LI循环并生成分层图表

时间:2014-07-07 12:52:44

标签: php mysql arrays

我有一个名为organization的表 如下所示

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(作为root用户)

如何才能正确地将其与各自的父母或下属联系起来?

我这样做但没有成功

$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 
    } 
    ?>

这个想法是必须输出每个

的干净无序列表

感谢您的帮助 谢谢

1 个答案:

答案 0 :(得分:0)

获取值后,需要先对它们进行分组,还可以进行递归函数,然后回显列表。考虑这个例子:

$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>