从csv中的行中提取值并将其求和 [英] Extract value from row in csv and sum it

查看:417
本文介绍了从csv中的行中提取值并将其求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在输入中得到了一个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

那是我用来获取csv,读取内容并将其放入数组的代码.

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);
};

我需要的是取每个季度的值,例如2010Q1、2010Q2、2010Q3、2010Q4,将其相加并除以4. csv或变量中.我尝试了很多解决方案,但都没有一个很好的解决方案.我尝试了strpos()方法,但每次只能读取一个值,但是之后我无法做其他事情. 有人可以解决我的问题吗?

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?

亲切的问候

推荐答案

这应该可以完成:

// $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);

输出:

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

在线演示.

这篇关于从csv中的行中提取值并将其求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆