将两个表的结果合并为JSON数据

时间:2019-04-14 21:55:19

标签: php mysql json

我有两个表wordsparagraphwords表如下:

+----+---------+--------------+--------+
| id | word_no | paragraph_no |  word  |
+----+---------+--------------+--------+
|  1 |    1    |       1      |  hello |
+----+---------+--------------+--------+
|  2 |    2    |       1      |  how   |
+----+---------+--------------+--------+
|  3 |    3    |       1      |  are   |
+----+---------+--------------+--------+
|  4 |    4    |       1      |  you   |
+----+---------+--------------+--------+

paragraph表如下:

+----+--------------+-------------------+
| id | paragraph_no |     paragraph     |
+----+--------------+-------------------+
|  1 |       1      | hello how are you |
+----+--------------+-------------------+

我希望words表中WHERE paragraph_no的所有列都是1,而段落表中具有相同WHERE子句的段落列都在一个JSON结果中。像这样:

{
    "1": [ <-- this is the paragraph number

        "words": [

            {
                "id": "1",
                "word_no": "1",
                "paragraph_no": "1",
                "word": "hello"
            },
            {
                "id": "2",
                "word_no": "2",
                "paragraph_no": "1",
                "word": "how"
            },

            // and so on...

        ],

        "paragraph": [

            {
                "paragraph": "hello how are you"
            }

        ]

    ]
}

请原谅我的模型,但我需要类似的东西。我目前仅能得到这些单词的PHP代码是:

$result = $conn->query("SELECT * FROM words WHERE paragraph_no = 1");

$data = array();

while ($row = $result->fetch_assoc()) $data[$row['paragraph_no']][] = $row;

$API_RESULT = json_encode($data, JSON_UNESCAPED_UNICODE);

echo $API_RESULT;

仅输出以下单词:

{
    "1": [ <-- this is the paragraph number

        {
            "id": "1",
            "word_no": "1",
            "paragraph_no": "1",
            "word": "hello"
        },
        {
            "id": "2",
            "word_no": "2",
            "paragraph_no": "1",
            "word": "how"
        },

        // and so on...

    ]
}

如何获取所需的JSON输出?

1 个答案:

答案 0 :(得分:1)

为了获得所需的结构,您需要执行两个SQL语句-一个用于获取所有单词,一个用于获取所有段落。

$result_w = $conn->query("SELECT * FROM words;");
$results_w = $result->fetch_all(MYSQLI_ASSOC);

$result_p = $conn->query("SELECT * FROM paragraphs;");
$results_p = $result->fetch_all(MYSQLI_ASSOC);

$paragraphs = [];
foreach($results_p as $key => $row) {
  $paragraphs[$row['id']] = $row;
}

$data = [];

foreach($results_w as $key => $row) {
  $p_no = $row['paragraph_no'];
  $data[$p_no]['words'] = $results_w;
  $data[$p_no]['paragraph'] = $paragraphs[$p_no];
}

您现在需要$data的输出吗?