<?php
  function removeKey(&$array, $key)
{
    if (is_array($array))
    {
        if (isset($array[$key]))
        {
            unset($array[$key]);
        }
        if (count($array) > 0)
        {
            foreach ($array as $k => $arr)
            {
                removeKey($array[$k], $key);
            }
        }
    }
}


  
    $hostName = "localhost";
    $username = "root";
    $password =  "loskyoc";
    $dbname = "newskybni";
    $dblink = mysqli_connect($hostName, $username, $password, $dbname) or die(mysqli_error());
    $menustring='';
    $id  =1;
	$chkid=1;
    $parentKey = 0;//  isset($_GET['id'])?$_GET['id']:0 ;//$_SESSION['login_addr'];
	//$parentKey = isset($_GET['id'])?$_GET['id']:1 ;//$_SESSION['login_addr'];
	$showrefer=true;
	//if($parentKey==1){ $showrefer=true;}
    //$sql = "SELECT * FROM `mtree` WHERE spid=0 ORDER BY idx ASC" ;
    //$data=array();
    //$result = mysqli_query($dblink, $sql);
    $data = membersTree($parentKey);
 
 
   
      function membersTree($parentKey)
      {
    $hostName = "localhost";
    $username = "root";
    $password =  "loskyoc";
    $dbname = "newskybni";
    $dblink = mysqli_connect($hostName, $username, $password, $dbname) or die(mysqli_error());
          global $chkid;
	      global $showrefer ;
		  global $menustring;
	      $row1=array(); 
          
          $sql = 'SELECT id, title,spid from mtree WHERE spid="'.$parentKey.'"';
		  
          $chkid++;
          $result = mysqli_query($dblink, $sql);
          $totalRows = mysqli_num_rows($result);
		  
          
          if($totalRows>0){
		   $menustring .='<ul>';	   
           while($value = mysqli_fetch_assoc($result)){
			 $menustring .='<li>'.$value['title']; 
			  
             $id = $value['id'] ;//$value['id'];
			 $row1[$id]['id'] = $value['id'];
             if($showrefer){ $row1[$id]['title'] = $value['title'].','.$value['spid'].','.$value['id'] ;}
			 else{ $row1[$id]['title'] = $value['title']; }
			 $row1[$id]['spid'] = $value['spid'];
			//$row1[$id]['tag'] =  count(membersTree($value['id']));
			  // $tag =  count(membersTree($value['id']));
              $sql2 = sprintf("SELECT id from mtree WHERE spid='%s' ",$value['id']);
		      $result2 = mysqli_query($dblink, $sql2);
              $totalRows2 = mysqli_num_rows($result2);
		      $tag =$totalRows2 ;
			 
     		// if($row1[$id]['tag'] >0){
			 if($tag >0){	  	 
			  $row1[$id]['children'] = array_values(membersTree($value['id']));
			 
			 }
			 
           }
		  $menustring .='</li>';  
		  }
		  $menustring .='</ul>';	
          return  $row1 ;
		  mysqli_close($dblink);
      }
      
 
   removeKey($data, 'id');
   removeKey($data, 'ref');
 
   $str1 = json_encode(array_values($data));
   $str1 =mb_substr($str1,1,-1);
   //echo $str1;
   echo  $menustring;
   mysqli_close($dblink);
?>
 