views:

462

answers:

3

I am using spacetree chart and I require JSON in hierarchical format. See sample required JSON format here. I have ID,ParentID,Name,Description fields in Mysql database table. Now How can I convert data in Hierarchical/nested JSON using PHP? I know json_encode($array). But, I require nested/Hierarchical php array for this. Let me know to do this.

A: 

If you have PHP json extension on your server installed, just use it on an array. The steps will be:

  1. Build PHP array with hierarchy based on mysql resutls
  2. call a json_encode($array) http://pl.php.net/manual/en/function.json-encode.php

If you don't have json_encode enabled on your server and cannot install it... You'll just have to write it by hand.

It'll be something like that (untested code warning):

function my_json_encode($array)
{
  $return = '{';
  $count = count($array);
  $i = 0;
  foreach ($array as $key => $val)
  {
    $return .= '"'.$key.'" : ';
    if (!is_array($val))
      $return .= '"'.$val.'"';
    else
      $return .= my_json_encode($val);
    if ($i < $count-1)
      $return .=",";
    $i++;
  }
  $return .= '}';
  return $return;
}
Tomasz Struczyński
This solution is a simple proof-of-concept and has to be enhanced. To add is, for example, object type support and some error handle. It's better to use json_encode anyway.
Tomasz Struczyński
Sorry, one more thing. If you're sending json, remember that you should set appropriate headers in response. Like: header('Content-type: application/json');
Tomasz Struczyński
Now my question is how to create nested/hierarchical php array?
Brij
+1  A: 

You're basically asking two questions here - 1) how to get an hierarchical php structure from a db table and 2) how to encode this structure in json. For the first question see, for example, my (old but working) code. For the second, I believe simple json_encode will work pretty well.

stereofrog
Thanks @stereofrog. You are very close to my object.the encoded format is different from required json. I don't require parent_ID and some additional stuff are coming.
Brij
A: 

Hi stereofrog, can you please help me, I have the same question. How to get an hierarchical php structure from a db table, in php array, or JSON, but with the following format:

[{ "attributes" : {"id" : "111"}, "data" : "Some node title", "children" : [ { "attributes" : { "id" : "555"}, "data" : "A sub node title here" } ], "state" : "open" }, { "attributes" : {"id" : "222"}, "data" : "Other main node", "children" : [ { "attributes" : { "id" : "666"}, "data" : "Another sub node" } ], "state" : "open" }]

My SQL table contains the fields: ID PARENT ORDER TITLE

Can you please help me with this? I'm going crazy trying to get this. I tried to modify your adj_tree function but I didn't got the array/json format I need.

Many thanks in advance. Daniel

daniel