Php多次平均

时间:2017-11-08 09:10:42

标签: php time average

当我试图获得多次数组时,它会向我返回false值,而数组有两个不同的日期时间。例如;

时间如下:23:30-30 - 01:30:30平均值应为:00:30:30

但现在它返回:12:30:30

我的数组:

    [0] => 22:50:20
    [1] => 05:37:42
    [2] => 04:21:15
    [3] => 02:51:00
    [4] => 00:35:09
    [5] => 01:28:45
    [6] => 23:15:47
    [7] => 02:50:01
    [8] => 03:32:04
    [9] => 00:09:17
    [10] => 23:49:10
    [11] => 23:26:37
    [12] => 00:35:56
    [13] => 04:54:00
    [14] => 00:55:06
    [15] => 23:32:03
    [16] => 02:27:27
    [17] => 02:22:42
    [18] => 01:49:47
    [19] => 03:25:36 ) 


    Average: 07:44:29

Php代码

date('h:i:s', array_sum(array_map('strtotime', $all_times)) / count($all_times));

1 个答案:

答案 0 :(得分:0)

根据您的上一条评论,您需要将前一天的 22:00 23:59 之间的所有时间视为一次,这样您就可以平均值一个连续的六小时,而不是一个24小时的一天。您可以通过从时间晚于晚上10点的所有值中减去一天来完成此操作:

$times = ['23:00', '01:00'];

$total = 0;

foreach ($times as $time) {
    $dt = new DateTime($time);

    // Treat all values later than 10pm as the previous day
    if ($dt->format('H') >= 22) {
        $dt->modify('-1 day');
    }

    // Sum the timestamps
    $total += $dt->format('U');
}

$average = $total / count ($times);
echo date('Y-m-d H:i:s', $average);

// 2017-11-08 00:00:00

请参阅https://eval.in/895375