我有csv导出的代码,由我使用,但问题是所有数据都在csv中导出一列。但我需要数据必须以列分隔,
<?php
$results= array(0=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"),1=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"));
$column = array("name","cname","agency","phone");
$writecolumn = array("Nome do Artista","Categoria","Agencia","Telefone");
$csv_export='';
for($i = 0; $i < count($column); $i++)
{
$csv_export.= $writecolumn[$i]."\t" ;
}
$csv_export.= "\n";
for($j = 0; $j < count($results); $j++)
{
for($i = 0; $i < count($column); $i++)
{
$csv_export.= $results[$j][$column[$i]]."\t";
}
$csv_export.= "\n";
}
$categoryname=$results[0]['cname'];
$filename = $categoryname."-Category-Artist-Data.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $csv_export;
exit;
?>
&#13;
。
答案 0 :(得分:0)
使用array_reduce,通过将函数应用于每个元素,将数组减少为单个值,并将初始值作为第三个参数传递,如下所示:
$result= array(0=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"),1=>array(name => "name_anil",agency=>"agency2",phone=>"234235",cname=>"Atleta_2"));
$csv_export = array_reduce($result, function($acc,$row) {
foreach($row as $key => $value) {
$acc .= $value;
$acc .= "\t";
}
$acc .= "\n";
return $acc;
},
"Nome do Artista\tCategoria\tAgencia\tTelefone\n")
$categoryname=$results[0]['cname'];
$filename = $categoryname."-Category-Artist-Data.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $csv_export;
exit;
答案 1 :(得分:0)
您的代码有分隔符(值分隔符)是&#39; tab&#39; (&#39; \吨&#39)。可能是您的CSV阅读软件需要一些配置才能开始使用&#39; tab&#39; (&#39; \ t&#39;)作为分隔符。我在下面更新了您的代码并使用&#39;,&#39;作为分隔符。 Microsoft Excel使用&#39;,&#39;作为默认分隔符。请尝试下面的代码,
<?php
$results= array(0=>array('name' => "anil",'agency'=>"",'phone' =>"234235",'cname'=>"Atleta"),1=>array('name' => "anil",'agency'=>"",'phone'=>"234235",'cname'=>"Atleta"));
$column = array("name","cname","agency","phone");
$writecolumn = array("Nome do Artista","Categoria","Agencia","Telefone");
$csv_export='';
for($i = 0; $i < count($column); $i++)
{
$csv_export.= $writecolumn[$i]."," ;
}
$csv_export.= "\r\n";
for($j = 0; $j < count($results); $j++)
{
for($i = 0; $i < count($column); $i++)
{
$csv_export.= $results[$j][$column[$i]].",";
}
$csv_export.= "\r\n";
}
$categoryname=$results[0]['cname'];
$filename = $categoryname."-Category-Artist-Data.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $csv_export;
exit;
?>
&#13;