使用此代码获得所需的输出
<?php
$connection = mysqli_connect('localhost', 'root', '', 'db_mani'); //connection
$sql = "SELECT * FROM users";
$result = mysqli_query($connection, $sql);
$usersArray = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
$usersArray[]= $row; ///will create array of users
}
}
function makeMenu($items, $parentId) //will create array in tree structure
{
$menu = array_filter($items, function ($item) use ($parentId) {
return $item['ref'] == $parentId;
});
foreach ($menu as &$item)
{
$subItems = makeMenu($items, $item['id']);
if (!empty($subItems))
{
$item['child'] = $subItems;
}
}
return $menu;
}
function print_users($usersArray,$ref = 'Admin')
{
$str ='<table border="1" width ="300" style="text-align:center;"><tr>';
foreach($usersArray as $user)
{
$str.='<td>'.$user['name'].' (Ref:'.$ref.')';
if(!empty($user['child']))
{
$str.= print_users($user['child'],$user['name']);
}
$str.='</td>';
}
$str.='</tr></table>';
return $str;
}
$usersArray = makeMenu($usersArray,0); ///call with parent id 0 for first time, this will give usres in tree structure
echo print_users($usersArray); // print users
?>
Run Code Online (Sandbox Code Playgroud)
最后结果 :
数据库结构:
我希望这能解决您的问题。谢谢。
归档时间: |
|
查看次数: |
375 次 |
最近记录: |