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 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决