<?php
//fetch.php
include_once "koneksidb.php";
//$connect = mysqli_connect("localhost", "root", "", "perpustakaandb");
$query = " SELECT * FROM m_pendahuluan_kategori";
$result = mysqli_query($koneksidb, $query);
$sub_data["id"] = 1;
$sub_data["name"] = 'Klasifikasi Putusan Pendahuluan';
$sub_data["text"] = 'Klasifikasi Putusan Pendahuluan';
$sub_data["parent_id"] = null;
$sub_data["level"] = 0;
$data[] = $sub_data;
while($row = mysqli_fetch_array($result))
{
 $sub_data["id"] = $row["id"];
 $sub_data["name"] = $row["nama"];
 $sub_data["text"] = $row["nama"];
 $sub_data["parent_id"] = $row["parent_id"];
 $sub_data["level"] = $row["level"];
 $data[] = $sub_data;
}
foreach($data as $key => &$value)
{
 $output[$value["id"]] = &$value;
}
foreach($data as $key => &$value)
{
 if($value["parent_id"] && isset($output[$value["parent_id"]]))
 {
  $output[$value["parent_id"]]["nodes"][] = &$value;
 }
}
foreach($data as $key => &$value)
{
 if($value["parent_id"] && isset($output[$value["parent_id"]]))
 {
  unset($data[$key]);
 }
}
mysqli_free_result($result);
echo json_encode($data);
/*echo '<pre>';
print_r($data);
echo '</pre>';*/

?>