Bastien Bastiens
Bastien Bastiens

Reputation: 419

Sum and Average in multi-dimentional arrays with php

I'm trying to get sum and average of visitors from the following multi-dimensional array :

Array([visitors] => Array(
[2015-06-12] => Array([0] => Array([value] => 29))
[2015-06-11] => Array([0] => Array([value] => 55))
...
))

I cannot manage to find a way to get the results i need as i get lost with "foreach".

Can anybody help please ?

Upvotes: 1

Views: 45

Answers (1)

Faiz Rasool
Faiz Rasool

Reputation: 1379

Use this

<?php

$mainarray = array('visitors' => Array(
        '2015-06-12' => Array(Array('value' => 29)),
        '2015-06-11' => Array(Array('value' => 55))));
$sum = 0;
$count = 0;

$visitor =  $mainarray['visitors'];
foreach ($visitor as $key => $val) {
    $sum += $val[0]['value'];
    $count++;
}
echo "Sum is " . $sum."<br>";
$average = ($sum / $count);
echo "Average is " .$average."<br>";;
?>

Upvotes: 2

Related Questions