I have a table called login
. In this i have 3 columns id, name and ref. people can register in the site with reference of another people. Admin
have no reference
so the ref value is 0
. A & c
comes under admin so their ref value is 1
. B,D and G
comes under A
so their ref value is 2
. E and F
comes under B
And a person can refer max of 3 people. . i need to get the out put in a table like this
Use this code get the desired output
<?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
?>
Final Result :
Database Structure:
I hope this will solve your problem. Thank you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With