The question was long, so I had to shorten it.
Anyway, I currently have the following table with the following results.
What I am doing is the following:
- Query all the answers associated to one question
- Encoding it after storing it into an array
This is my current query:
$stmt = "SELECT questions.question_text, answers.answer_text
FROM questions, answers, test
WHERE questions.question_id = answers.question_id
AND questions.test_id =1";
$result = $connection->query($stmt);
Which gives me this:
This is the PHP:
$encode = array();
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
Which gives me this output:
[
{
"question_text": "What is HTML?",
"answer_text": "HTML is a Hypertext Markup Language"
},
{
"question_text": "What is HTML?",
"answer_text": "HTML is a Hypertext Markup Language"
},
{
"question_text": "What is HTML?",
"answer_text": "HTML is a food"
},
{
"question_text": "What is HTML?",
"answer_text": "HTML is a food"
},
{
"question_text": "What is HTML?",
"answer_text": "HTML is an Asynchronous language"
},
{
"question_text": "What is HTML?",
"answer_text": "HTML is an Asynchronous language"
},
{
"question_text": "What is HTML?",
"answer_text": "HTML is a styling language"
},
{
"question_text": "What is HTML?",
"answer_text": "HTML is a styling language"
}
]
This is the desired output with json_encode:
"What is HTML?": {
"1": "HTML is a Hypertext Markup Language",
"2": "HTML is a food",
"3": "HTML is an Asynchronous language",
"4": "HTML is a styling language"
}
What I am currently getting is multiple single objects with one of the answers within them but always the answer associated to it. I wish to make a single object with all of the answers in it and the question representing the object. I really hope this makes sense. I am probably way off in my logic, so please forgive me for that.
I tried playing around with the while loop but I couldn't get it to work. Can someone lead me the right way towards achieving my desired output?
Thank you.
json_encode
nor mysql related functions. You have to reorganize your objects in$encode
yourself. – charlee Feb 28 at 20:11