2017-05-21 71 views
0

我正在爲我的項目生成一個考試報告csv文件,但我想自定義將在導出的csv文件上插入的數據。我怎麼做?我爲此使用php Codeigniter。使用php codeigniter格式生成的csv文件中的數據

截至目前,我的代碼可以生成一個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); 

    } 

回答

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

它的工作原理,但這時如果有什麼附加的數據來自數據庫?我嘗試將$ row2的值替換爲查詢。但是,它並沒有在csv單元格中顯示它顯示的數據'Array'和'Resource id#36'。 – dubiousconquest

+0

不會替換爲查詢。替換爲'$ row2 = $ result-> row_array()' – jagad89

+0

它的工作原理!非常感謝。 – dubiousconquest

相關問題