H
H
hollanditkzn2018-02-01 15:22:56
Yii
hollanditkzn, 2018-02-01 15:22:56

How to organize tests in php?

I have retrieved the data from the database. I build it so that 1 topic has 3 questions (maybe more than 10-15 questions) and each question has 3 answers (maybe more answers).
And they are all connected, and in order to bring them out, I had a question how to do it. If you do not sculpt your own array. My Sample Implementation
Controller

public function actionTesting($id)
    {
        $answear = Answers::find()->where(['id_thema' => $id])->all();

        return $this->render('test', [
            'model' => $model,
            'answear' => $answear,
        ]);
    }

in view
<?php
$this->title = $answear[0]->thema->name;
?>

<div class="test-testing">

    <?php foreach ($answear as $value){
        echo $value->question->name.'<br/>';
/** Вот тут непонятно как выводить*/
        echo $value->text.'<br/>';
    } ?>

</div>

Otherwise I get
Вопрос первый
один-два дня
Вопрос первый
более 5 дней
Вопрос первый
3-5 дней
Вопрос второй
да
Вопрос второй
нет
Вопрос второй
не постоянно, Меняется постоянно
Вопрос третий
да
Вопрос третий
нет
Вопрос третий
не помню

Do I need
Question one
- one or two days
- more than 5 days
- 3-5 days
How should I do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-02-01
@hollanditkzn

It is necessary to go through not the answer options, but questions, and through the connection, pull the answers to them

$questions = Question::find()
                          ->with('answers') //грузим одним запросом все ответы к выбранным вопросам
                           ->all();
foreach ($questions as $question){
        echo $question->name . '<br/>';
        foreach ($question->answers as $answer){
             echo $answer->text . '<br/>';
        }
}

But here the question is generally in the advisability of storing questions and answers in separate tables, I would store them in one. In this case, the answers are in the form of json and one more cell with the key of the correct answer.
id | question | answers | right
In afterFind we bring json into a regular php array using JsonHelper and use it.
foreach (Question::find()->all() as $question){
        echo $question->name . '<br/>';
        foreach ($question->answers as $key=>$answer){
             echo $answer . '<br/>';
        }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question