从单个表获取数据到多个json数组

时间:2019-01-16 07:13:02

标签: php mysql json

我正在尝试使用多个查询从单个表中获取数据。假设我有下表:

我的桌子:

enter image description here

我正在尝试获取PARA_NUMBER 1和PARA_NUMBER 2并使用以下查询将它们组合在一起

(SELECT * FROM `t_sen` WHERE `PARA_NUMBER` = 1) 
UNION 
(SELECT * FROM `t_sen` WHERE `PARA_NUMBER` = 2)

然后我得到JSON格式的结果,如下所示:

[
    {
        "ID": "1",
        "PARA_NUMBER": "1",
        "TEXT": "Hello"
    },
    {
        "ID": "2",
        "PARA_NUMBER": "1",
        "TEXT": "how"
    },
    // rest of the rows

    {
        "ID": "6",
        "PARA_NUMBER": "2",
        "TEXT": "Hope"
    },
    {
        "ID": "7",
        "PARA_NUMBER": "2",
        "TEXT": "you're"
    },
    // rest of the rows
]

但是,我想要这样的东西:

[
    "1": {
            "ID": "1",
            "PARA_NUMBER": "1",
            "TEXT": "Hello"
         },
         {
            "ID": "2",
            "PARA_NUMBER": "1",
            "TEXT": "how"
         },
         // rest of the rows

    "2": {
            "ID": "6",
            "PARA_NUMBER": "2",
            "TEXT": "Hope"
         },
         {
            "ID": "7",
            "PARA_NUMBER": "2",
            "TEXT": "you're"
         },
         // rest of the rows
]

每个PARA_NUMBER都有自己的分支。我正在使用非常简单的PHP代码来输出JSON数据:

$myquery = "
        (SELECT * FROM t_sen WHERE PARA_NUMBER = 1)
        UNION
        (SELECT * FROM t_sen WHERE PARA_NUMBER = 2)
    ";

$query = mysqli_query($conn, $myquery);

    if (!$query) {
        echo mysqli_error($conn);  //You need to put $conn here to display error.
        die();
    }

    $data = array();

    while($row = mysqli_fetch_assoc($query)) {
        $data[] = $row;
    }

    echo json_encode($data, JSON_PRETTY_PRINT);

2 个答案:

答案 0 :(得分:2)

如果您在PHP中使用mysqli接口,则可以执行以下操作(假设您的连接称为$conn):

$result = $conn->query('(SELECT * FROM `t_sen` WHERE `PARA_NUMBER` = 1) 
UNION 
(SELECT * FROM `t_sen` WHERE `PARA_NUMBER` = 2)');
$out = array();
while ($row = $result->fetch_assoc()) {
    $out[$row['PARA_NUMBER']][] = $row;
}
echo json_encode($out);

答案 1 :(得分:1)

即使尼克的答案已经奏效,但我认为没有必要使用UNION。为什么不改用IN

$result = $conn->query('SELECT * FROM `t_sen` WHERE `PARA_NUMBER` IN (1,2)');
$out = array();
while ($row = $result->fetch_assoc()) {
    $out[$row['PARA_NUMBER']][] = $row;
}
echo json_encode($out);