为什么fputcsv产生重复的列? [英] Why is fputcsv producing duplicate columns?

查看:61
本文介绍了为什么fputcsv产生重复的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向WordPress网站添加一个下载按钮,该按钮将查询我们的数据库,并以CSV格式提供结果.

I am adding a download button to a WordPress site that will query our database, and offer up the result as a CSV.

一切正常,所生成的CSV所返回的每一列都有重复的列.

我们已经检查了SQL查询,并且没有重复项.

We have checked the SQL query and it does not have duplicates.

这是我们生成CSV的方式:

Here's how we are generating the CSV:

$rows = //Call to SQL query function
$fp = fopen('php://output', 'w');
fputcsv($fp, array_keys($rows));

foreach ($rows as $row) {
  fputcsv($fp, $row);
}

$filename = "EventResults.csv";
header('Content-Type: text/csv');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=$filename");

我们将SQL返回值转换为如下所示的PHP数组:

We turn the SQL return into a PHP array like this:

 $sql = "SELECT * FROM TABLE";
 $statement = $this->db->prepare($sql);
 $statement->execute();
 return $statement->fetchAll();

结果如下:

Lance,Lance,Armstrong,Armstrong,DEX,DEX,70,70,1,1,60,60,SEC,SEC,"10; 20; 30; 40","10; 20; 30; 40"

什么时候它们看起来应该像这样:

When they should look like this:

Lance,Armstrong,DEX,70,1,60,SEC,"10; 20; 30; 40"

是什么原因导致重复,我们如何摆脱它们?

What is causing the duplicates, and how can we get rid of them?

推荐答案

PDO方法 fetchAll()具有参数 fetch_style ,该参数

The PDO method fetchAll() has a parameter fetch_style which as documented will return an array with both numerical and named associative keys causing you to have duplicates when you iterate over the array.

您可以使用此处中记录的PDO提取常量之一进行设置-它们都以 PDO :: FETCH _ 开头,并使用它们来获取关联数组( PDO :: FETCH_ASSOC )或数字数组( PDO :: FETCH_NUM )

You can set it using one of the PDO Fetch constants documented here - they all start with PDO::FETCH_ and use that to get either an associative array (PDO::FETCH_ASSOC) or a numerical array (PDO::FETCH_NUM)

return $statement->fetchAll(PDO::FETCH_ASSOC);

这篇关于为什么fputcsv产生重复的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆