导出为CSV-如何使用列名称数组将某些项目仅输出到CSV?

问题描述 投票:0回答:1

我正在尝试从mariaDB数据库进行CSV导出,网页用户可以在其中选择一些可选的列进行导出。我有一个捕获这些数据的表单,并且已经完成了所有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);

我在其中留下了一些注释掉的东西,我将其替换掉,以便您可以照原样“看到我的工作”。我目前在执行CSV文件每一行的循环中有array_intersect_key,但是我认为这不是正确的答案,但是我不确定我要执行的操作的名称是Google它。上面的代码当前将导致csv中应有数据的空白单元格。

$ fields包含我要导出的当前字段列表(强制性字段和用户已勾选的字段。)$ fieldsarrayforlinedata是我需要从循环遍历$ exporttocsvrow的CSV文件的这一行的内容数组的地方。

这有意义吗?

php
1个回答
0
投票
$fieldsarrayforlinedata = array_intersect_key($fields, $exporttocsvrow);

与此有关的两个问题。

  1. $fields中的字段名称为v​​alues,因此它无法按原样与array_intersect_key一起使用。您可以在while循环之前使用array_flip将它们转换为键。

    array_flip
  2. [$fields = array_flip($fields); 必须是$exporttocsvrow的第一个参数,因为它包含结果中所需的值。

array_intersect_key告诉我们:

array_intersect_key()返回一个数组,其中包含array1的所有条目,这些条目的所有参数中都包含键。

除此之外,看起来应该很好用。


p.s。考虑对多单词变量名使用camelCase或snake_case来提高可读性。

© www.soinside.com 2019 - 2024. All rights reserved.