I want to create a json string from two table's queries in one to many relations. I have done like this
$query = "SELECT id,name FROM sample1 ORDER BY id ASC" ;
$result = mysql_query($query) or die(mysql_error());
$parent = array() ;
while($row = mysql_fetch_array($result))
{
$parent[]= array("id"=>$row['id'],"name"=>$row['name']);
$query1 = "SELECT id,cid,cmessage FROM sample2 WHERE id = '$row[id]' ORDER BY cid ASC" ;
$result1 = mysql_query($query1) or die(mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$parent[] = array("id"=>$row1['id'],"cid"=>$row1['cid'],"comment"=>$row1['cmessage']);
}
} echo json_encode($parent);
it shows an output like this [{"id":"1","name":"Arathy"},{"id":"1","cid":"11","comment":"hai"},{"id":"1","cid":"111","comment":"exe"},{"id":"2","name":"Dhanya"},{"id":"2","cid":"22","comment":"yes"}]
But I want the format like as shown below ,
[
{
"id": "1",
"name": "Arathy",
"details": [
{
"id": "1",
"cid": "11",
"comment": "hai"
},
{
"id": "11",
"cid": "111",
"comment": "exe"
}
]
},
{
"id": "2",
"name": "Dhanya",
"details": [
{
"id": "2",
"cid": "22",
"comment": "yes"
}
]
} ]
Please help to correct