1

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

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

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 为介质,并将操作保存为 2010 年的唯一值,放入 csv 或在一个变量中。我尝试了很多解决方案,但没有一个效果很好。我尝试了 strpos() 方法,每次只能读取一个值,但之后我不能做其他事情。有没有人建议解决我的问题?

亲切的问候

4

2 回答 2

3
$brim = array();
$years = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $brim[] = $data;
    if (preg_match('/^(\d{4})Q(\d)/', $data[0], $match)) {
      $years[$match[1]][$match[2]] = $data[1];
    }
}
foreach ($years as &$year) {
  $year['avg'] = $avg = array_sum($year)/count($year);
}

在此之后,$years[2010]['avg']将包含 2010 年每个季度的平均值。

print_r($years);

Array
(
    [2010] => Array
        (
            [1] => 63.33447
            [2] => 61.29888
            [3] => 59.06448
            [4] => 57.62415
            [avg] => 60.330495
        )

    [2011] => Array
        (
            [1] => 60.97929
            [2] => 61.36082
            [3] => 59.88779
            [4] => 60.79407
            [avg] => 60.7554925
        )

)
于 2013-04-19T22:58:28.713 回答
1

这应该做的工作:

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

在线演示

于 2013-04-19T22:57:18.493 回答