本文介绍了在CSV导出中输出列标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此查询,可导出到一个csv文件.我无法弄清楚的唯一问题是,我还需要导出列标题,并使它们显示为全名",用户名",标志"和原因".下面是代码,它可以正常导出所有行,但是我不确定如何导出受关注行上方的列标题.

I have this query that exports to a csv file. It works fine the only thing i can't figure out is i need to export the column titles as well, and have them display as Full Name, UserName, Flag and Reason. Below is the code and it exports all the rows fine but I'm not sure how to export the column titles above the respected rows.

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=blackflag_bidders.csv");
header("Pragma: no-cache");
header("Expires: 0");




//SQL Query for Data
$sql = "SELECT ui.first_name, ui.last_name, u.username,
    if(u.flag=1,'BLK', if(u.flag=2,'NAA','')) flag,
    if(u.flag!=0, IFNULL(ui.note,''),'') reason
FROM user u
LEFT JOIN user_info ui ON ui.user_id=u.id
WHERE u.flag!=0;";

//Prepare Query, Bind Parameters, Excute Query
$STH = $sam_db->prepare($sql);
$STH->execute();



//Export to .CSV
$fp = fopen('php://output', 'w');
//fputcsv($fp);
while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
fclose($fp);

推荐答案

一种方法是通过关联获取第一个结果,无论如何,那些关联索引都是列.应用array_keys来获取这些内容,然后首先添加标题,然后添加第一行,然后循环其余部分.

One way would be to fetch the first result by associative, those associative indices are columns anyway. Apply array_keys to get those, then first add the headers, then the first fetched row, then loop the rest.

// first set
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
// $headers = array_map('ucfirst', $headers); // optional, capitalize first letter of headers
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row

while ($row = $STH->fetch(PDO::FETCH_NUM))  {
    fputcsv($fp,$row); // push the rest
}
fclose($fp);

这篇关于在CSV导出中输出列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:47