I'm trying to create a datatable that groups items based on a column name. In order to populate the table correctly I need to format the JSON with parent and child relationships but am having troubles. I'll be grabbing the data from MSSQL via PHP.
+---------------+-------+--------------+------------+------------+--------+
| ACTIVITY_NAME | GROUP | START_DATE | END_DATE | COMPLETED | TOTAL |
+---------------+-------+--------------+------------+------------+--------+
| Test | 1 | 04/30/2015 | 05/01/2015| 10 | 15 |
| Test | 2 | 04/30/2015 | 05/01/2015| 20 | 25 |
| Test2 | 1 | 05/2/2015 | 05/03/2015| 30 | 35 |
| Test2 | 2 | 05/2/2015 | 05/03/2015| 40 | 45 |
| Test2 | 3 | 05/2/2015 | 05/03/2015| 50 | 55 |
+---------------+-------+--------------+------------+------------+--------+
I need the JSON formatted like this with the parent objects being under the "data" and the children being under the "children". I'm having a hard time figuring out if I need to do two seperate queries, one for the rollup data in the parent and the second for the child rows. Any help would be appriecated.
Edit to add PHP:
<?php
include("connect.php");
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Set up and execute the query. */
$sql = "<QUERY>";
$stmt = sqlsrv_query( $conn, $sql);
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
} while ( sqlsrv_next_result($stmt) );
foreach ($json as $result) {
$data[$result['ACTIVITY_NAME']]['children'] = $result;
}
echo json_encode($data);
?>
I need this format: JSON blob: https://jsonblob.com/554b958be4b05c281ae9707e
{
"data": [
{
"ACTIVITY_NAME": "Test",
"children": [
{
"ACTIVITY_NAME": "Test",
"MAINTENANCE_GROUP": "1",
"START_DATE": "04/30/2015",
"END_DATE": "05/01/2015",
"COMPLETED": "10",
"TOTAL": "15"
},
{
"ACTIVITY_NAME": "Test",
"MAINTENANCE_GROUP": "2",
"START_DATE": "04/30/2015",
"END_DATE": "05/01/2015",
"COMPLETED": "20",
"TOTAL": "25"
}
]
},
{
"ACTIVITY_NAME": "Test2",
"children": [
{
"ACTIVITY_NAME": "Test2",
"MAINTENANCE_GROUP": "1",
"START_DATE": "05/2/2015",
"END_DATE": "05/03/2015",
"COMPLETED": "30",
"TOTAL": "35"
},
{
"ACTIVITY_NAME": "Test2",
"MAINTENANCE_GROUP": "1",
"START_DATE": "05/2/2015",
"END_DATE": "05/03/2015",
"COMPLETED": "40",
"TOTAL": "45"
},
{
"ACTIVITY_NAME": "Test2",
"MAINTENANCE_GROUP": "1",
"START_DATE": "05/2/2015",
"END_DATE": "05/03/2015",
"COMPLETED": "50",
"TOTAL": "55"
}
]
}
]
}