I need help formatting my JSON correctly. Create parent objects for each action, and then add children to them. In the examples below, this will be one parent action for “Test” with two children and another parent for “Test2” with three children. I contacted in two jsonblobs with the format I get and in the format I need. Any help would be greatly appreciated.
+---------------+-------+--------------+------------+------------+--------+
| 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 |
+---------------+-------+--------------+------------+------------+--------+
PHP:
<?php
include("connect.php");
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$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[data][][$result['ACTIVITY_NAME']]['children'] = $result;
}
echo json_encode($data);
?>
This is what I get : https://jsonblob.com/5550c921e4b002ae4e370469
This is what I need : https://jsonblob.com/5550c942e4b002ae4e370471
Edit -
This is what ended up with my working script as follows:
<?php
include("connect.php");
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$sql = "<query> ";
$stmt = sqlsrv_query($conn, $sql);
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$name = $row['ACTIVITY_NAME'];
$group = '';
$sdate = '';
$edate = '';
$completed = '';
$total = '';
$perc = '';
if (! isset($data[$name])) {
$data[$name] = array(
'ACTIVITY_NAME' => $name,
'MAINTENANCE_GROUP' => $group,
'START_DATE' => $sdate,
'END_DATE' => $edate,
'COMPLETED' => $completed,
'TOTAL_CLUSTERS' => $total,
'COMPLETE_PERC' => $perc,
'children' => array(),
);
}
$data[$name]['children'][] = $row;
}
$data = array_values($data);
echo json_encode(array('data' => $data));
?>
source
share