简体   繁体   English

数组到CSV移位的行

[英]Array to CSV shifted rows

I am trying to convert the below array to a downloadable csv with three columns and three rows. 我试图将以下数组转换为具有三列和三行的可下载的csv。 For some reason, the below functions create four columns instead of three with some of the rows shifted over. 出于某种原因,下面的函数创建了四列而不是三列,其中一些行被移位。

I was wondering if someone can help me identify why this is? 我想知道是否有人可以帮我确定原因是什么?

Many thanks in advance! 提前谢谢了!

$ary = array(
                array("1", "Bob", "Saget"),
                array("2", "Luke", "Skywalker"),
                array("3", "Owen", "Wilson")
            );

$csv = arrayToCsv($ary);
downloadCSV($csv);


function arrayToCsv($array) {
    $csv = array();
    foreach ($array as $item) {
        if (is_array($item)) {
            $csv[] = arrayToCsv($item) . "\n";
        } else {
            $csv[] = $item;
        }
    }
    return implode(',', $csv);
} 


function downloadCSV($csv){
    $fileName = 'customer-list.csv';

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . $fileName);
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

    echo $csv;
    exit;
}

Your outer call to arrayToCsv() calls itself for each element of the array. 您对arrayToCsv()外部调用会为数组的每个元素调用自身。 The inner call puts commas between each element of the sub-array, and then adds a newline to the end. 内部调用在子数组的每个元素之间放置逗号,然后在结尾添加换行符。 The outer call collects these in a new array, and then separates them with commas. 外部调用在新数组中收集它们,然后用逗号分隔它们。 This puts an extra comma at the beginning of each line except the first. 这会在除第一行之外的每行的开头添加一个额外的逗号。

You need to process the outer array differently from the sub-arrays. 您需要以不同于子数组的方式处理外部数组。 Implode with , when processing the sub-arrays, implode with \\n when processing the outer array. 与内爆,处理所述子阵列时,与内爆\\n处理外阵列时。

function arrayToCsv($array) {
    return implode("\n", array_map(function($subarray) {
        return implode(",", $subarray);
    }, $array));
}

Or you could just use fputcsv : 或者你可以使用fputcsv

$fp = fopen("php://stdout", "w");
foreach ($ary as $row) {
    fputcsv($fp, $row);
}
fclose($fp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM