I have scenario where one user can refer two codes to other one will become right and other left.Now this right can have two child left and right and so on same for left child user.... So this is binary tree like strucutre

so i am selecting a user from database which current login user now binary tree will be displayed.I have coloumn in database which is postion which will have value left or right.So for current login user there will be rows returned one is left and other right now i want to continue to process this thing till end of tree and save all these value in suitable array structure which must determined this is top most user it have left and right and both lchild and rchild and two child each respectively.

By current approcach]

<?php
session_start();
/**function chain($user){
    include('database.php');
    $query="SELECT username, position FROM users WHERE sponsor_id='$user'";
    $check=mysqli_query($connect,$query) or die(mysqli_error($connect));
    $temp=array();
    while ($row=mysqli_fetch_assoc($check)){
    $child_name=$row['username'];
    $child_pos=$row['position'];

    $data=array();
    if($child_pos=="left"){
     $data['parent']=$user;
     $data['lchild'] =$child_name;
     $data['lpos'] =$child_pos;
     $temp[]=$data;
     chain($child_name);
    }else if($child_pos=="right"){  
    $data['parent']=$user;
    $data['rchild'] =$child_name;
    $data['rpos'] =$child_pos;
    $temp[]=$data;
    chain($child_name);
    }else if($child_pos==''){
     echo "No User found"; 
    }

}

}
*/
$user=$_SESSION['username'];
chain($user);

?>

plz help me in this banging my head from two days :)