I'm trying to get a json from mysql to use it for creating a tree view with help of bootstrap treeview ajax. But my php produces the wrong json.
I can't understand where do {"1":
also "2"
"6"
and "7"
comes from, since I don't have them in my table.
PHP
<?php
//fetch.php
$connect = mysqli_connect("hostname", "user", "", "dbname");
$query = "SELECT * FROM vtiger_customers";
$result = mysqli_query($connect, $query);
//$output = array();
while($row = mysqli_fetch_array($result))
{
$sub_data["id"] = $row["customersid"];
$sub_data["customer_name"] = $row["customer_name"];
$sub_data["type"] = $row["type"];
if ($row["society"]=='')
$sub_data["parent_id"] = "0";
else $sub_data["parent_id"] = $row["society"];
$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]);
}
}
echo json_encode($data);
?>
JSON output that i get
{"1":{"id":"78","customer_name":"Holding_1","type":"EPC","parent_id":"","nodes": [{"id":"77","customer_name":"Ship owner","type":"Shipowner","parent_id":"78"}]},"2":{"id":"79","customer_name":"Holding_2","type":"EPC","parent_id":"","nodes":[{"id":"80","customer_name":"Ship owner 2","type":"Shipowner","parent_id":"79","nodes":[{"id":"82","customer_name":"Sub Ship owner","type":"Shipowner","parent_id":"80"}]},{"id":"81","customer_name":"Ship owner 1","type":"Shipowner","parent_id":"79"}]},"6":{"id":"83","customer_name":"Ship owner","type":"Shipowner","parent_id":""},"7":{"id":"84","customer_name":"Shipyard","type":"Shipyard","parent_id":""}}
JSON format which i need
[{"id":"78","customer_name":"Holding_1","type":"EPC","parent_id":"","nodes": [{"id":"77","customer_name":"Ship owner","type":"Shipowner","parent_id":"78"}]},{"id":"79","customer_name":"Holding_2","type":"EPC","parent_id":"","nodes":[{"id":"80","customer_name":"Ship owner 2","type":"Shipowner","parent_id":"79","nodes":[{"id":"82","customer_name":"Sub Ship owner","type":"Shipowner","parent_id":"80"}]},{"id":"81","customer_name":"Ship owner 1","type":"Shipowner","parent_id":"79"}]},{"id":"83","customer_name":"Ship owner","type":"Shipowner","parent_id":""},{"id":"84","customer_name":"Shipyard","type":"Shipyard","parent_id":""}]
MySQL Table
customers_id customers_number society type customer_name
78 46546 EPC Holding_1
79 53456 EPC Holding_2
83 763645 Shipowner Ship owner
77 324543 78 Shipowner Ship owner
84 63465435 Shipyard Shipyard
80 534523 79 Shipowner Ship owner
81 836754 79 Shipowner Ship owner
82 8746546 80 Shipowner Sub Ship owner