I currently have a MySQL table set up as follows:
ID | FirstName | LastName | Gender | FParent | MParent | CreationTimeStamp |
---|---|---|---|---|---|---|
1 | Lilly | Carbeso | 1 | 0 | 0 | 2021-07-23 12:14:40 |
2 | Cameron | Colebourne | 0 | 0 | 0 | 2021-07-23 12:16:42 |
3 | Liam | Nugent | 0 | 1 | 2 | 2021-07-23 12:17:55 |
4 | Craig | Newell | 0 | 1 | 2 | 2021-07-23 12:27:00 |
And I am currently parsing the full table to output a JSON array that looks like this:
[{"ID":"1","FirstName":"Lilly","LastName":"Carbeso","Gender":"1","FParent":"0","MParent":"0","CreationTimeStamp":"2021-07-23 12:14:40"},{"ID":"2","FirstName":"Cameron","LastName":"Colebourne","Gender":"0","FParent":"0","MParent":"0","CreationTimeStamp":"2021-07-23 12:16:42"},{"ID":"3","FirstName":"Liam","LastName":"Nugent","Gender":"0","FParent":"1","MParent":"2","CreationTimeStamp":"2021-07-23 12:17:55"},{"ID":"4","FirstName":"Craig","LastName":"Newell","Gender":"0","FParent":"1","MParent":"2","CreationTimeStamp":"2021-07-23 12:27:00"}]
Using the current php:
<?php
require_once "gene-config.php";
$connection = new mysqli($servername, $username, $password, $dbname) or die("Error " . mysqli_error($connection));
$sql = "select * from gtable";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
mysqli_close($connection);
?>
The format that I would like the data to look like and what D3JS uses is below:
{
"name": "Eve",
"children": [
{
"name": "Cain"
},
{
"name": "Seth",
"children": [
{
"name": "Enos"
},
{
"name": "Noam"
}
]
},
{
"name": "Abel"
},
{
"name": "Awan",
"children": [
{
"name": "Enoch"
}
]
},
{
"name": "Azura"
}
]
}
"FParent" is the ID value of the female parent "MParent" is the ID value of the male parent
What I am struggling to understand is how is it possible to parse a JSON object from a MySQL table that would nest the children based on the IDs, "FParent" and "MParent" values?