php如何从csv文件转换数据?

时间:2018-04-19 10:05:08

标签: php

我有一个csv文件,其中包含

等数据
shelfmark, centuries
foo-0001, 2000s;
bar-1234, 1200s, 1300s;
baz-IK-1234, 0100s, 0200s, 0300s;
and so on...

我想导入数据并将其转换为只有两列的格式:

shelfmark, century
foo-0001, 2000s;
bar-1234, 1200s;
bar-1234, 1300s;
baz-IK-1234, 0100s;
baz-IK-1234, 0200s;
baz-IK-1234, 0300s;
and so on...

并将其写入新的csv文件中。

如果行包含多个世纪的值,我需要帮助创建新行的代码。

我的尝试:

<?php
    $csv = array_map('str_getcsv', file($file));
    array_walk($csv, function(&$a) use ($csv) {
      // check if row has more than two column entries
      if
      // if so then split the first century value into a new row 
      // do so until no more century value is in the row left and continue with next row
      $data = array_combine($csv[0], $a);
    });
    // write into new csv file
    $fp = fopen('php://output', 'w');
    foreach ( $data as $line ) {
        $val = explode(",", $line);
        fputcsv($fp, $val);
    }
    fclose($fp);

?> 

1 个答案:

答案 0 :(得分:1)

您可以通过循环最终内容并使用array_shift()取下行标题('foo-0001')然后将其添加到数组中的每个剩余元素来简化过程。

这使用fwrite()来维护内容格式。

$csv = array_map('str_getcsv', file($file));
// Take the titles out of the main list of lines
$titles = array_shift($csv);
$fp = fopen('php://output', 'w');
// Add the header row
fwrite($fp, implode(",", $titles).PHP_EOL);
foreach ( $csv as $line ) {
    $header = array_shift($line);   // Remove the first part from the array
    foreach ( $line as $entry )  {
        fwrite($fp, $header.",". trim($entry,";").";".PHP_EOL);
    }
}
fclose($fp);