dsdv76767671 2013-04-19 22:41
浏览 84
已采纳

从csv中的行中提取值并对其求和

I'm getting a csv file in input, that is a example of the content:

TIME,Value
2010,77.77046
2010,60.32812
2010Q1,63.33447
2010Q2,61.29888
2010Q3,59.06448
2010Q4,57.62415
2011,60.75586
2011Q1,60.97929
2011Q2,61.36082
2011Q3,59.88779
2011Q4,60.79407

That is the code i use to take the csv, read the content and put it into an array.

if (($handle = fopen("csvExtractTor.csv", "r")) !== FALSE) {
 # Set the parent multidimensional array key to 0.
    $nn = 0;
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        # Count the total keys in the row.
        $c = count($data);
        # Populate the multidimensional array.
        for ($x=0;$x<$c;$x++)
        {
            $brim[$nn][$x] = $data[$x];
        }
        $nn++;
    }
    # Close the File.
    fclose($handle);
};

What i need, is to take the values of each quarters​​, for example, 2010Q1, 2010Q2, 2010Q3, 2010Q4, sum it and divided / 4 for the medium and save the operation to a unique value in 2010, into the csv or in a variable. I've tried lots of solutions but none works good. I tried the method strpos(), i was able to read only a value per time, but after that i cannot do other things. Does anyone have an advise to solve my problem?

kind regards

  • 写回答

2条回答 默认 最新

  • dqfwcj0030 2013-04-19 22:57
    关注

    This should do the job:

    // $csv = file_get_contents('file.csv');
    $csv = 'TIME,Value
    2010,77.77046
    2010,60.32812
    2010Q1,63.33447
    2010Q2,61.29888
    2010Q3,59.06448
    2010Q4,57.62415
    2011,60.75586
    2011Q1,60.97929
    2011Q2,61.36082
    2011Q3,59.88779
    2011Q4,60.79407';
    $array = array();
    
    preg_replace_callback('/((\d{4})Q\d),(\d+(?:\.\d+))/', function($matches) use(&$array){
        if(isset($array[$matches[2]])){
            $array[$matches[2]] += ($matches[3]/4);
        }else{
            $array[$matches[2]] = ($matches[3]/4);
        }
        return($matches[1]);
    },$csv);
    print_r($array);
    

    Output:

    Array
    (
        [2010] => 60.330495
        [2011] => 60.7554925
    )
    

    Online demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题