I'm working with three MySQL tables that are related in a PHP application. There are tests which have many questions, and the questions have many answers. What I would like to do is loop through the data as follows:
foreach($tests as $test)
{
echo $test->testName;
foreach($test->questions as $question)
{
echo $question->questionText;
foreach($question->answers as $answer)
{
echo $answer->answerText;
}
}
}
What I would like to know is what the MySQL query and PHP code would be to loop through it in this manner?
edit MySQL can't return arrays like this, what I should have said is what would the MySQL + PHP code look like.
For clarity, the tables are tests, questions and answers. The questions table contains a test_id column, and the answers contains a question_id
Thanks!
The structure I'm looking to get back would be something along the lines of:
array(
'testName' = 'Test name string',
'questions' = array(
array(
'questionId' = 1,
'questionText' = 'Question string',
'answers' = array(
array(
'answerId' = 1,
'answerText' = 'Answer string'
),
array(
'answerId' = 2,
'answerText' = 'Answer string'
)
)
)
)
);
edit
My current implementation is as follows, what I wanted to do was eager load the data rather than perform so many queries
$tests = getTests();
foreach($tests as $test){
$questions = getQuestions($test->id);
foreach($questions as $question){
$answers = getAnswers($question->id);
foreach($answers as $answer){
// do answer things
}
}
}