我有两个如下所示的表格,它们显示了我们表格中的表格结构。
表1
id comment
1 abc
2 xyz
3 pqr
表2
id1 table1ID reply
1 1 efg
2 1 mnr
3 2 slq
这里我想以 JSON 格式发送数据,如下
<?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";
}
?>
以下显示 JSON 表示形式的结果(我需要如下生成)需要输出。
{
"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"
}
]
}
]
}
这里,如果第一个评论需要生成多个回复后,如果一条评论有多个回复,我想生成如上所述的 JSON。
以下是我现在的输出。
{
"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"
}
]
}
]
}
最佳答案
您必须更改 while()
代码并在其外部添加一些行,如下所示:
$finalData = array();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$finalData[$row["id"]]['id'] = $row["id"];
$finalData[$row["id"]]['comment'] = $row["comment"];
$finalData[$row["id"]]['reply'][] = array(
"id1" => $row['id1'],
"table1ID" => $row['table1ID'],
"reply" => $row['reply']
);
}
$Output["status"] = 1;
$Output["msg"] = "comment";
$Output["comment"]= array_values($finalData);
$connection = null;
echo json_encode($Output);
注意:- 您正在 while()
循环内覆盖数组,并且您的代码对SQL注入(inject),所以请使用PDO
准备好的语句
使用准备好的语句
的代码示例:
<?php
$ID = $req->id;
try {
$sql= "SELECT table1.*, table2.* FROM table1 LEFT JOIN table2 ON table1.id = table2.table1ID WHERE id = :id";
$sth = $dbh->prepare($sql);
$sth->execute(array(':id' =>$ID));
$finalData = array();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$finalData[$row["id"]]['id'] = $row["id"];
$finalData[$row["id"]]['comment'] = $row["comment"];
$finalData[$row["id"]]['reply'][] = array(
"id1" => $row['id1'],
"table1ID" => $row['table1ID'],
"reply" => $row['reply']
);
}
$Output["status"] = 1;
$Output["msg"] = "comment";
$Output["comment"]= array_values($finalData);
$connection = null;
echo json_encode($Output);
}
}
catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
关于php - 如何在php中生成json并在多个数组中嵌套一个数组(用于匹配值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56521660/