简体   繁体   中英

Convert MySQL Query Result to Hierarchical Data - D3

As mentioned above i'm trying out the plot a chart using d3 where in i'd require the data to be in Parent Child relationship but i couldn't figure it out how to convert the MySQL query result to JSON parent child format.

Help provided will be very thankful.

I'm trying to replicate the chart in the below URL :

Zoomable Partition Layout (click on the partitions to zoom up or down the tree)

Data in MySQL :

Column1          Column2            Column3
First Top          -                  1500
First Child       First Top            500
Second Child      First Top            500
Third Child       First Top            500
First Sub-Child   First Child          250
First Sub-Child   First Child          250
Second Sub-Child  Second Child         250
Second Sub-Child  Second Child         250
Third Sub-Child   Third Child          250
Third Sub-Child   Third Child          250

Desired Data Format :

{
    "name": "First Top",
    "children": [
    {
        "name": "First Child",
        "children": [
        {"name": "First Sub-Child", "size": 250},
        {"name": "First Sub-Child", "size": 250}
        ]
    },
    {
        "name": "Second Child",
        "children": [
        {"name": "Second Sub-Child", "size": 250},
        {"name": "Second Sub-Child", "size": 250}
        ]
    },
    {
        "name": "Third Child",
        "children": [
        {"name": "Third Sub-Child", "size": 250},
        {"name": "Third Sub-Child", "size": 250}
        ]
    }
    ]
}

Here's some pseudo-code, assuming one level of hierarchy:

  • get the parent/child rows from the database ( select t1.parent, t1.item, size from tree t1, tree t2 where t1.parent=t2.item )
  • loop through the rows:
    • if parent is different than previous parent and previous parent is set:
      • push object onto array
      • start a new object
    • add child and size to object
  • push last object onto array
  • get root object (where parent is null)
  • encode object as json with root object; see Create JSON-object the correct way
  • output json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM