如何用负值PHP取平均值?

时间:2015-05-23 11:01:55

标签: php datetime math

我有一个阵列说:

array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");

我尝试使用strtime但它给了我错误,因为它无法将负值转换为时间戳。还有别的办法吗?

2 个答案:

答案 0 :(得分:2)

在重新阅读问题之后,我做了一个小片段,平均值是一个数字的总和。所以我猜这应该是正确的。要绕过负时间戳,您只需计算绝对时间戳,将其设为负值并将其添加到总和中。

<?php

    $timings = array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
    //$timings = array("-10:10:20", "-10:10:20", "-10:10:20", "-10:10:20");

    $totalTime = 0;
    foreach($timings as $timing) {
        $isNegativeTime = strpos($timing, '-') !== false;
        $time = strtotime(str_replace('-', '', $timing));
        if ($isNegativeTime) $time *= -1;
        $totalTime += $time;
    }

    $avgTiming = $totalTime / count($timings);
    $isNegativeAvgTime = $avgTiming < 0;
    $avgTiming = date('h:i:s', abs($avgTiming));
    echo ($isNegativeAvgTime ? '-':'').$avgTiming;

答案 1 :(得分:-2)

<?php 
$moredownvotes = array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");

$nb_lol = count($moredownvotes);

for ($i = 0; $i < ($nb_lol - 1); ++$i)
{
    $pattern = '/^-(.*)/';
    $replacement = '${1}';
    $moredownvotes[$i] = preg_replace($pattern, $replacement, $moredownvotes[$i]);
}

print "<pre>";
print_r($moredownvotes);
print "</pre>";
?>

结果:

Array
(
    [0] => 10:10:20
    [1] => 20:00:10
    [2] => 14:15:00
    [3] => 08:10:00
)

现在你可以使用DateTime函数或者你想要

$date = DateTime::createFromFormat('H:i:s', $moredownvotes[$i]);
echo date_format($date, 'H:i:s');

**结果**:10:10:20

PHP.net createFromFormat function