I have two tables like below, they show the table structure as we have in our table.
table1
id comment
1 abc
2 xyz
3 pqr
table2
id1 table1ID reply
1 1 efg
2 1 mnr
3 2 slq
Here I want to send data as JSON as follows
<?php
$ID = $req->id;
try {
$sql= "SELECT table1.*, table2.* FROM table1 LEFT JOIN table2 ON table1.id = table2.table1ID WHERE id = '".$ID."'";
$res= $connection->query($sql);
while($row = $res->fetch(PDO::FETCH_ASSOC)) {
$lclData1[] = array(
"id" => $row["id"],
"comment" => $row['comment'],
"reply" => array(
"id1" => $row['id1'],
"table1ID" => $row['table1ID'],
"reply" => $row['reply'],
)
);
$Output["status"] = 1;
$Output["msg"] = "comment";
$Output["comment"] = $lclData1;
$connection = null;
echo json_encode($Output);
}
}
catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
Following shows result as in JSON representation(I need to produce like below) OUTPUT NEEDED.
{
"status": 1,
"message": "data",
"comment": [
{
"id": "1",
"comment": "abc",
"reply":
[
{
"id1": 1,
"table1ID": 1,
"reply": "efg"
},
{
"id1": 2,
"table1ID": 1,
"reply": "mnr"
}
]
},
{
"id": "2",
"comment": "xyz",
"reply":
[
{
"id1": 3,
"table1ID": 2,
"reply": "slq"
}
]
}
]
}
Here I want to produce JSON like above if one comment has more than one reply after first comment need to produce multiple replies.
Following is my output right now.
{
"status": 1,
"message": "data",
"comment": [
{
"id": "1",
"comment": "abc",
"reply":
[
{
"id1": 1,
"table1ID": 1,
"reply": "efg"
}
]
},
{
"id": "1",
"comment": "abc",
"reply":
[
{
"id1": 2,
"table1ID": 1,
"reply": "mnr"
}
]
},
{
"id": "2",
"comment": "xyz",
"reply":
[
{
"id1": 3,
"table1ID": 2,
"reply": "slq"
}
]
}
]
}
prepared statementsofPDOlibrary