Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a function to get a tree structured output

enter image description here

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. Adminhave 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

enter image description here

like image 808
Juice Avatar asked Aug 13 '16 10:08

Juice


1 Answers

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 :

enter image description here

Database Structure:

enter image description here

I hope this will solve your problem. Thank you.

like image 92
Manjeet Barnala Avatar answered Oct 16 '22 09:10

Manjeet Barnala