[英]PHP Export Array to CSV
我目前有一個查詢,該查詢返回下面的數組。當我嘗試將數據導出到CSV文件時,我看到了兩次數據(重復列,而不是行)。有人可以向我解釋為什么嗎? (我希望每個記錄僅顯示一次)
Array
(
[0] => Array
(
[0] => 6991
[id] => 6991
[1] => 8588
[work_num] => 8588
[2] => Test123
[name] => Test123
[3] => 1407154
[deployed] => 1407154
[4] => 2015-10-13
[created_date] => 2015-10-13
)
)
這是我用來導出數據的代碼
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('id','Work Number','Name','Deployed','Date'));
$get_data = $CLASSNAME->FuntionName(Parameters);
foreach($get_data as $data_row) {
fputcsv($output, $data_row);
}
fclose($output);
如果使用MySQL,則將mysql_fetch_array
替換為mysql_fetch_row
。
mysql_fetch_array
返回結果集,既是數字數組又是關聯數組。 mysql_fetch_row
將僅將數值集返回結果集。
修復您的傳入數據(使用PDO時,使用PDO :: FETCH_ASSOC或PDO :: FETCH_NUM而不是PDO :: FETCH_BOTH,這是默認設置),或者在放入csv時命名您的列:
foreach($get_data as $data_row) {
fputcsv($output, array(
$data_row['id'],
$data_row['work_num'],
$data_row['name'],
$data_row['deployed'],
$data_row['created_date']
));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.