簡體   English   中英

導出為 CSV - 如何將我的列名數組用於 output 僅將部分項目用於 CSV?

[英]Export as CSV - how do I use my array of column names to output only some of the items to CSV?

我正在嘗試從 mariaDB 數據庫中進行 CSV 導出,其中 web 頁面用戶可以選擇 Z99938282F04071852ZEF16 列可選。 我有一個捕獲這些數據的表單,並且我已經完成了所有 PHP 代碼,以達到我想要在導出過程中使用的數據庫中的列標題數組的位置。 ($safefieldsarray 是上面代碼中的可選字段數組。)

我的 CSV 導出在這里松散地基於這個https://www.codexworld.com/export-data-to-csv-file-using-php-mysql/ (添加了上述導出內容的選項。)

我正在努力的代碼塊就在這里。

//create a file pointer
$f = fopen('php://memory', 'w');

                                                                                                                                                        //set column headers
$fields = array('ID', 'Name', 'em', 'type', 'reason', 'result', 'status', 'notes', 'datetime', 'requestedby', 'requestedbycitrixid', 'week', 'period', 'year', 'historylog');
$fields = $fields+$safefieldsarray;
fputcsv($f, $fields, $delimiter);
//create $linedata information, formatted in a php assoc row format.
// $linedata1 = implode('"], $exporttocsvrow["' ,$fields);
// $linedata2 .= '$exporttocsvrow["'.$linedata1;
// $linedata3 .= $linedata2 .'"]';
// $linedatasplit = explode(",",$linedata3);

// $fieldsarrayforlinedata = array();
// foreach ($fields as $value) {
// array_push($fieldsarrayforlinedata , '$exporttocsvrow["'.$value.'"]');
// }


//output each row of the data, format line as csv and write to file pointer
while($exporttocsvrow = $exporttocsvresult->fetch_assoc()){
$fieldsarrayforlinedata = array_intersect_key($fields, $exporttocsvrow);
fputcsv($f, $fieldsarrayforlinedata, $delimiter);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $safefilename . '";');
//output all remaining data on a file pointer
fpassthru($f);

我在那里留下了一些我替換的注釋掉的東西,這樣你就可以“看到我的工作”了。 我目前有 array_intersect_key 在循環中執行 CSV 文件的每一行,但我認為這不是正確的答案,但我不確定我想要做的事情的名稱是什么給谷歌它。 上面的代碼目前會在 csv 中產生大量空白單元格,數據應該在其中。

$fields 包含我要導出的當前字段列表(強制性字段和用戶勾選的字段。) $fieldsarrayforlinedata 是我需要從 $正在循環的 exporttocsvrow。

這有意義嗎?

$fieldsarrayforlinedata = array_intersect_key($fields, $exporttocsvrow);

這有兩個問題。

  1. $fields中的字段名稱是values ,因此它不能按原樣與array_intersect_key一起使用。 您可以在 while 循環之前使用array_flip將它們轉換為鍵。

     $fields = array_flip($fields);
  2. $exporttocsvrow需要是array_intersect_key的第一個參數,因為它包含您想要在結果中的值。

function 的 PHP 文檔告訴我們:

array_intersect_key() 返回一個數組,其中包含 array1 的所有條目,這些條目的鍵存在於所有 arguments 中。

除此之外,它看起來應該工作得很好。


ps 考慮對多字變量名使用camelCase 或snake_case 以提高可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM