我正在尝试使用多个查询从单个表中获取数据。假设我有下表:
我的桌子:
我正在尝试获取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);
答案 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)