我正在使用 PHP 应用程序中相关的三个 MySQL 表。有很多问题的测试,问题有很多答案。我想做的是循环遍历数据,如下所示:
foreach($tests as $test)
{
echo $test->testName;
foreach($test->questions as $question)
{
echo $question->questionText;
foreach($question->answers as $answer)
{
echo $answer->answerText;
}
}
}
我想知道的是 MySQL 查询和 PHP 代码会以这种方式循环遍历它吗?
编辑MySQL 不能返回这样的数组,我应该说的是 MySQL + PHP 代码会是什么样子。
为清楚起见,表格是测试、问题和答案。questions 表包含一个 test_id 列,answers 包含一个 question_id
谢谢!
我希望找回的结构类似于:
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'
)
)
)
)
);
编辑
我目前的实现如下,我想做的是急切地加载数据而不是执行这么多的查询
$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
}
}
}