PHP生成不正确的json

时间:2018-01-23 00:39:26

标签: php jquery mysql json

我正在尝试从mysql中获取一个json,以便在bootstrap treeview ajax的帮助下使用它来创建树视图。但是我的php产生了错误的json。

我无法理解Lazy<ConcurrentDictionary> {"1": "2""6"来自何处,因为我的表格中没有{。}}。

PHP

"7"

我得到的JSON输出

<?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格式

  {"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":""}}

MySQL表

[{"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":""}]

2 个答案:

答案 0 :(得分:1)

初始$data数组是一个索引数组。为每个键分配一个项目数组。每个项目数组都有键parent_id和值&gt; = 0 ...

... 1267是初始$data数组中的索引,其中{的值为{相应项目数组的{1}}键为parent_id

为了获得你需要的东西,你必须在将它作为json编码的字符串打印之前重置0的数组索引:

$data

答案 1 :(得分:-1)

需要数据库规范化。

CREATE TABLE vtiger_customers(   customers_id int(11)NOT NULL,   customer_number int(11)NOT NULL,   customer_name varchar(255)NOT NULL,   society int(11)NOT NULL,   type varchar(255)NOT NULL )ENGINE = InnoDB DEFAULT CHARSET = latin1;