douxin2003 2016-01-07 13:27
浏览 35
已采纳

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

I'm trying to display an average result from the database to the view but I keep getting this error:

A PHP Error was encountered

Severity: Notice

Message: Array to string conversion

Filename: views/resultview.php

Line Number: 38

Here is the code from the Controller:

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

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

The function from the model is the following:

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

and the code from the view it is:

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

I can't seam to find out why it does this.

Thank you for your help guys.

  • 写回答

4条回答 默认 最新

  • douzhongqiu5032 2016-01-07 13:59
    关注

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

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?