I'm trying to get data from a single table using multiple queries. Suppose I have the following table:
MY TABLE:
I'm trying to get PARA_NUMBER 1 and PARA_NUMBER 2 and combining them using this query:
(SELECT * FROM `t_sen` WHERE `PARA_NUMBER` = 1)
UNION
(SELECT * FROM `t_sen` WHERE `PARA_NUMBER` = 2)
And then I get the results in JSON format which looks something like this:
[
{
"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
]
However, I want something like this:
[
"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
]
Where every PARA_NUMBER have their own branches. I'm using very simple PHP code to output the JSON data:
$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);
