I am trying to create an array of custom json objects while traversing an array of results from a db query. However I m unable to get the correct response from the code.
I have tried creating arrays and traversing it. Below is my code to show what all I have tried. P.S. I am newbie to php so, I am sorry if its a rookie mistake or anything.
$response = array();
while($row = $result->fetch_assoc()){
$flag = false;
$sample_obj = json_encode(json_decode("{}"));
$index = 0;
$length = count($response);
for($x = 0; $x < $length; $x++){
if($response[$x]->session_id == $row->session_id){
$sample_obj = $row;
$flag = true;
$index = $x;
break;
}
}
if($flag == true){
$sample_array = array();
$sample_array[] = $row;
$response[$index]->sessions[] = $row;
} else {
$sample_array = array();
$sample_array[] = $row;
$sample_obj["session_id"] = $row->session_id;
$sample_obj["sessions"] = array();
$sample_obj["sessions"] = $sample_array;
$response[] = $sample_obj;
}
// $response[] = $row;
}
$res["statusCode"] = 201;
$res["success"] = true;
$res["records_found"] = true;
$res["results"] = $response;
header('Content-Type: application/json;charset:utf-8');
echo json_encode($res,JSON_PRETTY_PRINT);
I want output like
{
"statusCode": 201,
"success": true,
"records_found": true,
"results": [
{
"session_id" : 1,
"sessions" : [
{
"session_id" : 1,
"creation_time" : "some_timestamp",
"active_session" : true
},
{
"session_id" : 1,
"creation_time" : "some_timestamp",
"active_session" : false
},
{
"session_id" : 1,
"creation_time" : "some_timestamp",
"active_session" : false
}
]
}
]
}
But I m getting very wrong output like :
{
"statusCode": 201,
"success": true,
"records_found": true,
"results": [
"A}"
]
}
I dont know why this "A}" is being shown instead of my session array.