LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Calculating Average in PHP Array? (https://www.linuxquestions.org/questions/programming-9/calculating-average-in-php-array-785011/)

your_shadow03 01-27-2010 01:27 AM

Calculating Average in PHP Array?
 
Guys,

I need help with array in php. All I was having the following columns:

Code:


Time          4 6 7 10 11 avg 4 6 7 10 11 avg

Now Like the Above there were more variables defined through script:
Code:

$cols = array(
        array(0,1),
        array(1,1),
        array(2,1),
        array(3,1),
        array(4,1),
        array(5,1),
        array(6,1),
        array(0,16),
        array(1,16),
        array(2,16),
        array(3,16),
        array(4,16),
        array(5,16),
        array(6,16),
        array(0,19),
        array(1,19),
        array(2,19),
        array(3,19),
        array(4,19),
        array(5,19),
        array(6,19),
        array(7,2),
        array(8,2),
        array(9,2),
        array(10,2),
        array(11,2),
        array(7,23),
        array(8,23),
        array(9,23),
        array(10,23),
        array(11,23),
        array(7,24),
        array(8,24),
        array(9,24),
        array(10,24),
        array(11,24),
        array(7,25),
        array(9,25),
  array(11,2),
        array(7,23),
        array(8,23),
        array(9,23),
        array(10,23),
        array(11,23),
        array(7,24),
        array(8,24),
        array(9,24),
        array(10,24),
        array(11,24),
        array(7,25),
        array(9,25),
        array(10,25),
        array(11,25),
    );

    echo '<tr><td>'.date('d/m/y H:i:').(date('s')<30?'00':'30').'</td>';
    $last_col = 0;
    $sum = 0;
    $count = 0;
    foreach ( $cols as $col ) {
        $count++;
        if ($col[1]<>$last_col) {
            if ($last_col>0) {
                printf('<td>%0.2f</td>',$sum/$count);
            }
            $last_col=$col[1];
            $count = 0;
            $sum = 0;
        }
        $sum += $data[$col[0]+1][$col[1]];
        echo '<td>'.$data[$col[0]+1][$col[1]].'</td>';
    }
    printf('<td>%0.2f</td>',$sum/$count);
    echo "</tr>\n";
    exit;
}

Now what the above code is doing is calculating average of above values from columns{1-?,4-?)..likewise

Say If I remove two Machine and calculate the avg.
How Gonna I do that??

graemef 01-27-2010 04:19 AM

I think that you need to explain you problem a little more:

What does the array signify, I can see that it is an array of arrays but that doesn't mean anything to me?
What is you expected output?
What do you mean by remove a machine?

Also looking at the code what is the variable $data?


All times are GMT -5. The time now is 05:41 PM.