繁体   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