Monday, 13 May 2019

Creating hierarchical JSON from MySQL results and PHP for D3.js tree?

I am trying to create the following JSON (much simplified...) from database results using PHP:

{
    "name": "Bob",
    "children": [{
            "name": "Ted",
            "children": [{
                "name": "Fred"
            }]
        },
        {
            "name": "Carol",
            "children": [{
                "name": "Harry"
            }]
        },
        {
            "name": "Alice",
            "children": [{
                "name": "Mary"
            }]
        }
    ]
}

The database tables:

Table 'level_1':

level_1_pk| level_1_name
-------------------------
 1 | Bob  


Table 'level_2':

level_2_pk| level_2_name | level_1_fk
-------------------------
 1 | Ted                 | 1
 2 | Carol               | 1
 3 | Alice               | 1


Table 'level_3':

level_3_pk| level_3_name | level_2_fk
-------------------------
 1 | Fred                | 1
 2 | Harry               | 2
 3 | Mary                | 3

The code:

$query = "SELECT * 
FROM level_1
LEFT JOIN level_2
ON level_1.level_1_pk = level_2.level_1_fk";
$result = $connection->query($query);
 while ($row = mysqli_fetch_assoc($result)){
        $data[$row['level_1_name']] [] = array(
            "name" => $row['level_2_name']
            );
    }

echo json_encode($data);

Produces:

{"Bob":[{"name":"Ted"},{"name":"Carol"},{"name":"Alice"}]}

Question:

How can I get the next level, level_3, and include the text "children" and level_3 children in the JSON as required in the JSON defined above?

I imagine I will need a recursive function given more nesting/levels in the JSON.



from Creating hierarchical JSON from MySQL results and PHP for D3.js tree?

No comments:

Post a Comment