duanjiang7505 2016-11-14 20:14
浏览 38
已采纳

过滤PHP数组键并计算平均值

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 :)

  • 写回答

1条回答 默认 最新

  • dongranding3909 2016-11-14 20:33
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算