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 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表