php - 如何在php中生成json并在多个数组中嵌套一个数组(用于匹配值)

标签 php json

我有两个如下所示的表格,它们显示了我们表格中的表格结构。

表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

准备好的语句

PDO::prepare

使用准备好的语句的代码示例:

<?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/

相关文章:

json - 如何从 Swift Codable 中排除属性?

javascript - 按描述过滤 JSON 对象 Express JS/Underscore JS

php - (PHPUnit) PHP fatal error : Uncaught Error: Call to undefined function each()

php - 在 PHP 中编译正则表达式

php - Laravel action() 帮助程序忽略 APP_URL 环境变量

javascript - Node WriteFile 不使用下划线编写我需要的对象。写入整个对象

c# - 如何在 C# API 中返回 JSON

php - 特殊字符和多语言的严重问题

php - 显示数据库中的重复项数 [SQL]

javascript - 在 javascript 中正确获取 json