使用php codeigniter

时间:2017-05-21 07:24:35

标签: php codeigniter csv

我正在为我的项目生成考试报告csv文件,但我想自定义将在导出的csv文件中插入的数据。我怎么做?我正在使用php Codeigniter。

截至目前,我的代码可以生成一个csv文件,其中包含问题以及该问题的正确和错误答案的数量。

这是下载文件的图片。 Generated CSV File

但我希望它看起来像这样:

Wanted Result

这是我的控制器和型号: 控制器:

public function csv_report($exam_no){
    $this->load->model('instant_model');
    $median = $this->median($exam_no);

    $this->instant_model->exportToCSV($exam_no);
}

型号:

public function exportToCSV($exam_no){

        $this->load->dbutil();
        $this->load->helper('file');
        $this->load->helper('download');

        $delimiter = ",";      
        $newline = "\r\n";
        $filename = "exam_report.csv";
        $query = " SELECT DISTINCT(questions.question_id), questions.question, 
            (SELECT count(score) FROM exam_set WHERE exam_no = '$exam_no' AND score > 0 AND questions.question_id = exam_set.question_id) AS correct , 
            (SELECT count(score) FROM exam_set WHERE exam_no = '$exam_no' AND score = 0 AND questions.question_id = exam_set.question_id) AS wrong 
            FROM questions INNER JOIN exam_set ON (questions.question_id = exam_set.question_id) WHERE exam_no = '$exam_no';";

         $result = $this->db->query($query);
        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

    } 

1 个答案:

答案 0 :(得分:0)

所以你已经为你的结果输出了csv,但你只想将数据附加到它。因此,让我们创建一个为我们提供CSV行的功能。

function get_csv_line(array $row, $delim = ',', $newline = "\n", $enclosure = '"')
{
 $line = array();
 foreach ($row as $item)
 {
    $line[] = $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure;
 }
 $out .= implode($delim, $line).$newline;
 return $out;
}

编辑您的代码块,如下所示

$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
$row1 = array('mean','maximum','minimum','variance','median');
// replace your values.
$row2 = array(4.66,5,3,7,8);
$out1 = get_csv_line($row1, $delimiter, $newline);
$out2 = get_csv_line($row2, $delimiter, $newline);
$data .= $out1.$out2;

 force_download($filename, $data);