如何在PHP中使用多个数组中的一个嵌套嵌套数组生产JSON(用于匹配值)

时间:2019-06-10 06:44:05

标签: php json

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

表1

imshow

table2

id    comment
1     abc
2     xyz
3     pqr

在这里,我想按如下所示以JSON格式发送数据

id1   table1ID     reply
1      1           efg
2      1           mnr
3      2           slq

以下将结果显示为JSON表示形式(我需要像下面那样产生)OUTPUT NEEDED。

 <?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"
        }
      ]
    }
 ]
}

2 个答案:

答案 0 :(得分:1)

您正在循环覆盖答复数据,因此在您的情况下它仅显示一条记录,

将您的Output数组更改为我的并检查一次,

while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
    $Output["status"]                         = 1;
    $Output["msg"]                            = "comment";
    $Output["comment"][$row['id']]['id']                  = $row['id'];
    $Output["comment"][$row['id']]['comment']             = $row['comment'];
    // I changed here to catch all replies in reply array
    $Output["comment"][$row['id']]['reply'][] = [
        "id1"      => $row['id1'],
        "table1ID" => $row['table1ID'],
        "reply"    => $row['reply'],
    ];
    $connection = null;
    // reset indexes
    $Output['comment'] = array_values($Output['comment']); 
    echo json_encode($Output);
}

编辑

也许您需要单独的lclData1,

$lclData1 = [];
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
    $lclData1[$row['id']]['id']      = $row['id'];
    $lclData1[$row['id']]['comment'] = $row['comment'];
    // I changed here to catch all replies in reply array
    $lclData1[$row['id']]['reply'][] = [
        "id1"      => $row['id1'],
        "table1ID" => $row['table1ID'],
        "reply"    => $row['reply'],
    ];
}
$Output["status"]  = 1;
$Output["msg"]     = "comment";
$Output["comment"] = $lclData1;
$connection        = null;
// reset indexes
$Output['comment'] = array_values($Output['comment']);
echo json_encode($Output);

答案 1 :(得分:1)

您必须更改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 INJECTION也是开放的,所以请使用prepared statements中的PDO

PDO::prepare

使用prepared statements的代码示例:

<?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";
}
?>