将行输出到csv

flseospp  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(363)

我有一个脚本,它可以在终端输出中成功地打印头和行,但是当我尝试对csv输出执行相同的操作时,它失败了,并说它需要一个数组。
我想试着得到一个简单的csv,最好是在excel中打开不同的列

print("Frame,Group,Average Days,Total Units Sold,Total Placements\n");
//$file = fopen("contacts.csv","w");

foreach($groupedByFrame as $frame){
print($frame['frame'].','.$frame['group'].','.round($frame['avg'],3).','.$frame['qty'].','.$frame['placements']."\n");
  //fputcsv($file,explode(',',$frame));
}

//fclose($file);
vyswwuz2

vyswwuz21#

如果要更改 $frame 数组,您可以创建另一个:

$file = fopen("contacts.csv","w");

// header
$header = ['Frame','Group','Average Days','Total Units Sold','Total Placements'];
fputcsv($file, $header);

// data
foreach($groupedByFrame as $frame)
{
    $array = [
        $frame['frame'],
        $frame['group'],
        round($frame['avg'],3),
        $frame['qty'],
        $frame['placements']
    ];
    fputcsv($file, $array);
}
fclose($file);

如果要输出 $frame 您可以直接使用:

$file = fopen("contacts.csv","w");
$header = ['Frame','Group','Average Days','Total Units Sold','Total Placements'];
fputcsv($file, $header);
foreach($groupedByFrame as $frame)
{
    fputcsv($file, $frame);
}
fclose($file);
xfyts7mz

xfyts7mz2#

你不需要分解内部数组,它已经是一个数组了。
试试这个:

//print("Frame,Group,Average Days,Total Units Sold,Total Placements\n");
$file = fopen("contacts.csv","w");

foreach($groupedByFrame as $frame) 
{ 

 //print($frame['frame'].','.$frame['group'].','.round($frame['avg'],3).','.$frame['qty'].','.$frame['placements']."\n");
  fputcsv($file,$frame);
}

fclose($file);

相关问题