Codeigniter中的数组到字符串转换错误

Nyn*_*eve 1 php codeigniter average

我试图从数据库到视图显示平均结果,但我不断收到此错误:

遇到 PHP 错误

严重性:注意

消息:数组到字符串的转换

文件名:views/resultview.php

行号:38

这是来自控制器的代码:

$average['avg'] = $this->quiz->getAverage($quizid);

$this->load->view('resultview',array('quiz' => $quiz,
                                     'score' => $score, 
                                     'average_score' => $average));
Run Code Online (Sandbox Code Playgroud)

该模型的函数如下:

   function getAverage($quiz) 
    {
    //get percentage from the database 

    $this->db->select_avg('score');
    $this->db->where('id', $quiz);
    $res = $this->db->get('userScoreQuiz');

    if ($res->num_rows() != 1) {
        // there should only be one row - anything else is an error
        return false;
    }
    return $res->result_array();
}
Run Code Online (Sandbox Code Playgroud)

从视图来看,代码是:

<h4> Avg. score on all previous attempts: <?php echo $average_score['avg'] ?>   %</h4> 
Run Code Online (Sandbox Code Playgroud)

我无法找出它为什么会这样做。

谢谢你们的帮助。

Ila*_*nus 5

That's too much of coding you got going on, Here is an Elegant solution:

function getAverage($quiz)
{
    //get percentage from the database
    $query = $this->db->select('AVG(score) as average_score')->from('userScoreQuiz')->where('id', $quiz)->get();
    return $query->row()->average_score;
}
Run Code Online (Sandbox Code Playgroud)

For your view

$data['quiz']          = //fill this area
$data['average_score'] = $this->quiz->getAverage($quizid);
$data['score']         = //fill this area

$this->load->view('resultview', $data);
Run Code Online (Sandbox Code Playgroud)

And they will be accessable as $quiz, $average_score, $score