Fabrizio Cocco Fabrizio Cocco - 18 days ago 6
PHP Question

Filter PHP Array Keys and calculating mean value

I have an array with dates as keys and prices as values. Like this:

Array
(
[2016-11-11] => 25.05
[2016-11-12] => 25.05
[2016-11-13] => 25.05
[2016-11-14] => 25.05
...
)


Now i need to calculate the mean value of today - 1 till today - 8. Of course it should also calculating correctly if there is less than 8 entries.

I'm thinking of extracting the keys and filter for the values and put that all in for loop. But i bet there will be a better way. I am at least happy for an idea in which direction to start with. May you help me?

The "today" i defined like this:

date_default_timezone_set("Europe/Berlin");
$timestamp = time();
$today = date("Y-m-d",$timestamp);


edit:
The output should be like

$last_week_mean = "value" of key[today-1] + "value" of key [today-2]

+ ... / count(amount of key values in this range)


But i don't know how to build this query/filter - thing :)

Answer

You can use array_filter with ARRAY_FILTER_USE_KEY to get the specific date range you want. But after than, you don't need to use a loop to calculate the average. You can just use sum / count of the filtered array.

$d1 = date('Y-m-d', strtotime('8 days ago'));
$d2 = date('Y-m-d', strtotime('1 day ago'));

$range = array_filter($your_array, function($date_string) use ($d1, $d2) {
    return $date_string >= $d1 && $date_string <= $d2;
}, ARRAY_FILTER_USE_KEY);

$average = array_sum($range) / count($range);

Also, just in case you're getting your initial array from a database, it would most likely be easier and more efficient to only select the dates you want to begin with.

Comments