I started learning json and developing a quiz app which fetches json from a php page to display it as html. I am selecting data from mysql table with php and printing it as json.
<?php
header('Access-Control-Allow-Origin: *');
header("Cache-Control: no-cache");
header('Content-Type: application/json');
include("dbcon.php");
$sql = "SELECT * FROM quiz;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode($row, JSON_PRETTY_PRINT)."\r\n";
}
}
else {
echo "nodata";
}
$conn->close();
?>
the result is:
{
"id": "1",
"question": "ques1?",
"opt1": "Microsoft",
"opt2": "W3C",
"opt3": "Google",
"opt4": "IBM",
"answer": "W3C"
}
{
"id": "2",
"question": "ques2?",
"opt1": "Yahoo",
"opt2": "Google",
"opt3": "Bing",
"opt4": "DuckDuckGo",
"answer": "Google"
}
this code works perfectly fine and pretty prints json. But how to print the same key value as an array so the output is like-
{
"id":[ "1", "2" ],
"question":[ "ques1?", "ques2?" ],
"opt1":[ "asd", "fgh" ],
"opt2":[ "qwe", "rty" ],
"opt3":[ "qwer", "vbbn" ],
"opt4":[ "asdfg", "ascvb" ],
"answer":[ "asd", "fgh" ],
}
I believe the result i expect will make it simple to read data from it using javascript by something like this:-
var q1 = myObj.question[0];
I saw many questions with the same title but they are all different cases. please provide a solution and correct my stupidity if I am wrong.
$questions, then use$questions[] = $row;. With that all done, you can finish withjson_encode($questions)to get your single array of question objects.[{"id": ..., "question": ..., ...}, {"id": ..., ...}].json_encode()generates valid JSON but concatenating two valid JSON strings (as your current code does) doesn't make a valid JSON. JSON is just a string representation of some data structure. You have to build the data structure you need and encode it as JSON only once, at the end.