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

报告相同问题?

悬赏问题

  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗