将数据安装到CSV列的明智

  • 本文关键字:CSV 数据 安装 php
  • 更新时间 :
  • 英文 :


我已经尝试过,它对行明智的工作非常有用。

// output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
// do not cache the file
header('Pragma: no-cache');
header('Expires: 0');
// create a file pointer connected to the output stream
$file = fopen('php://output', 'w');
// send the column headers
fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));
// Sample data. This can be fetched from mysql too
$data = array(
    array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
    array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
    array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
    array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
    array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55')
);
// output each row of the data
foreach ($data as $row)
{
    fputcsv($file, $row);
}
exit();

,但我希望它像明智的列一样安装。意思是,现在是

'Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'
'Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'
'Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'

,但我想要这样的

'Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'
'Data 11', 'Data 21', 'Data 31', 'Data 41', 'Data 51'

这是可能的还是有什么技巧可以做到?预先感谢。

一种方法是首先组织您的数组以与嵌套的foreach循环匹配所需的结果

$result = [];                        // Grouped result array
foreach ($data as $value) {          // Loop thru each data array
    foreach ($value as $k => $v) {   // Loop thru each data
        $result[$k][] = $v;          // Group all elements with same index
    }
}
// output each row of the data
foreach ($result as $row)            // Loop thru grouped result array
{
    fputcsv($file, $row);
}

样本结果阵列就像这样

$result = array (
    array ('Data 11', 'Data 21', 'Data 31', 'Data 41', 'Data 51'),
    array ('Data 12', 'Data 22', 'Data 32', 'Data 42', 'Data 52'),
    array ('Data 13', 'Data 23', 'Data 33', 'Data 43', 'Data 53'),
    array ('Data 14', 'Data 24', 'Data 34', 'Data 44', 'Data 54'),
    array ('Data 15', 'Data 25', 'Data 35', 'Data 45', 'Data 55')
);

最新更新