我有一个数组说:如何平均负值PHP的时间?
array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
我尝试使用strtime,但它给我的错误,因为它不能负的值转换为时间戳。有没有其他办法?
我有一个数组说:如何平均负值PHP的时间?
array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
我尝试使用strtime,但它给我的错误,因为它不能负的值转换为时间戳。有没有其他办法?
<?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
)
NOW u可以使用日期时间函数或W/Eü要
$date = DateTime::createFromFormat('H:i:s', $moredownvotes[$i]);
echo date_format($date, 'H:i:s');
** **结果:10:10:20
它仍然是一串字符串 - 他想让字符串变成时间戳。看到... – Falt4rm
重读这个问题后,我做了一个小片段,平均值是一个数字的总和。所以我猜这应该是正确的。要绕过负面的时间戳,您只需计算绝对值,使其为负值并将其添加到总和中。
<?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;
显示您在您的问题的尝试 – Rizier123
什么意思-20小时。现在是20小时吗?在这种情况下,积极的价值呢? – splash58
您可以使用https://github.com/vascowhite/Time来计算平均时间。 –