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

时间:2016-01-07 13:27:04

标签: php codeigniter average

我正在尝试将数据库的平均结果显示给视图,但我一直收到此错误:

遇到PHP错误

严重性:注意

消息:数组到字符串转换

文件名:views / resultview.php

行号:38

以下是Controller的代码:

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

$this->load->view('resultview',array('quiz' => $quiz,
                                     'score' => $score, 
                                     'average_score' => $average));

模型中的功能如下:

   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();
}

以及视图中的代码:

<h4> Avg. score on all previous attempts: <?php echo $average_score['avg'] ?>   %</h4> 

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

感谢您的帮助。

4 个答案:

答案 0 :(得分:3)

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->row()->score;
}

来自docs

$this->db->select_avg('age');
$query = $this->db->get('members'); // Produces: SELECT AVG(age) as age FROM members

答案 1 :(得分:2)

这是你进行的编码过多,这是一个优雅的解决方案:

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;
}

供您查看

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

$this->load->view('resultview', $data);

它们可以$quiz, $average_score, $score

访问

答案 2 :(得分:0)

替换

DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">

echo $average_score['avg'];

因为那不是一个变量,即数组

答案 3 :(得分:0)

codeigniter result_array()以数组形式返回数据。数组索引从0索引开始。

“$ average_score ['avg']”这应该是未定义的索引。如果您不想更改函数,请尝试将结果数组作为$ average_score ['avg'] [0] ['score']访问。

如果你想避免额外的数组索引,那么使用row()而不是result_array()返回结果。