php - Extract value from row in csv and sum it -


i'm getting csv file in input, example of 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 code use take csv, read content , put array.

if (($handle = fopen("csvextracttor.csv", "r")) !== false) {  # set parent multidimensional array key 0.     $nn = 0;     while (($data = fgetcsv($handle, 1000, ",")) !== false) {         # count total keys in row.         $c = count($data);         # populate multidimensional array.         ($x=0;$x<$c;$x++)         {             $brim[$nn][$x] = $data[$x];         }         $nn++;     }     # close file.     fclose($handle); }; 

what need, take values of each quarters​​, example, 2010q1, 2010q2, 2010q3, 2010q4, sum , divided / 4 medium , save operation unique value in 2010, csv or in variable. i've tried lots of solutions none works good. tried method strpos(), able read value per time, after cannot other things. have advise solve problem?

kind regards

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


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -