Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating average value for array with PHP?

My head is exploding with this. I can't seem to create a working solution.

I have a file in this format:

99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15

I want to calculate average values from third column for each id from the first column.

This seems so easy but I can't get this to work. How do you get averages for any said id from first column?

EDIT:

Some sample code I've written before:

$file = file_get_contents("results.txt");


$file = explode("
", $file);

$howMany = count($file);

for($a = 0;$a<$howMany;$a++)
{

$row = explode("|", $file[$a]);
$id = $row[0];



$howManyAlready = count($bigTable[$id]);

$bigTable[$id][$howManyAlready] = $row[2];

}

I've added the code. So far it gets the results into an array ( with offset corresponding to its id ) But I am having trouble with how to get those results and calculate average for each id and then present it on the screen.

like image 955
user3010273 Avatar asked May 22 '26 16:05

user3010273


2 Answers

Something like this should definitely work..

<?php
$arr=array();
$arrv=array_filter(file('myfile.txt'),'strlen');
foreach($arrv as $v)
{
    array_push($arr,@array_pop(explode('|',$v)));
}
echo $avg = array_sum($arr)/count($arr);
like image 107
Shankar Narayana Damodaran Avatar answered May 25 '26 06:05

Shankar Narayana Damodaran


You can try doing this :

$file = file_get_contents("results.txt");
$file = explode("
", $file);

$valuesPerID = Array();

foreach($file as $row)
{

    $row_array = explode("|", $row);

    $id = $row_array[0];

    if(!array_key_exists($id, $valuesPerID))
    {
        $valuesPerID[$id] = Array();
    }

    $valuesPerID[$id][] = $row_array[2];

}

Now in the $valuesPerID array, you'll have all your ID as keys, and for each ID, all the values associated with the said ID. They you can easily calculate the average of these values !

like image 33
Theox Avatar answered May 25 '26 06:05

Theox