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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了