duangai1916 2018-04-19 10:05
浏览 26
已采纳

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

I have a csv file that has data like

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

I want to import the data and convert it to a format that has only two columns:

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...

And write it in a new csv-file.

I need help with the code of creating new rows if a row contains more than one century value.

My attempt:

<?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条回答 默认 最新

  • douyingyu5573 2018-04-19 10:17
    关注

    You can simplify the process by looping over the final content and just taking off the line header ( 'foo-0001' ) using array_shift() and then adding this to each of the remaining elements in the array.

    This uses fwrite() to maintain the content format.

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器