gpt4 book ai didi

PHP 计算 'downtime'

转载 作者:行者123 更新时间:2023-11-29 05:42:08 25 4
gpt4 key购买 nike

我用 PHP 编写了一个程序,它在运行时存储在 MySQL 数据库中。显示程序是否正常工作的表格如下所示:

Table_name: downtime
Working(int) Time(datetime)
1 2011-05-06 15:18:55
0 2011-05-06 15:20:21
1 2011-05-06 15:20:24
0 2011-05-06 16:05:13
1 2011-05-06 16:05:15
0 2011-05-06 16:27:59
1 2011-05-06 16:28:01
0 2011-05-06 16:37:35
1 2011-05-06 16:37:37

现在我想检索日期之间的“停机时间”。假设日期 1 是 2011-05-06 15:20:24,日期 2 是 2011-05-06 16:28:15,那么我希望脚本返回该期间 1 和 0 之间的差值之和.我该怎么做?

重要的是要知道如果日期 1 例如是 2011-05-06 15:20:22,则停机时间会增加两秒。很难想出(几乎)完美的解决方案。

最佳答案

这段代码应该可以工作,我已经用您的示例数据对其进行了测试:

// Example data
// Note: assumes $data is sorted by date already
$data = array(
"2011-05-06 15:18:55"=>1,
"2011-05-06 15:20:21"=>0,
"2011-05-06 15:20:24"=>0,
"2011-05-06 16:05:13"=>0,
"2011-05-06 16:05:15"=>0,
"2011-05-06 16:27:59"=>1,
"2011-05-06 16:28:01"=>0,
"2011-05-06 16:37:35"=>0,
"2011-05-06 16:37:37"=>1
);

$startTime = strtotime("2011-05-06 15:18:55");
$endTime = strtotime("2011-05-06 16:28:01");

$totalUptime = 0;
$lastUptime = 0;

foreach ($data as $dateString => $isWorking)
{
$timestamp = strtotime($dateString);

if ($lastWorking && $lastTimestamp)
{
$allowedStart = $lastTimestamp;
if ($allowedStart<$startTime)
$allowedStart = $startTime;

$allowedEnd = $timestamp;
if ($allowedEnd>$endTime)
$allowedEnd = $endTime;

$diff = $allowedEnd-$allowedStart;

if ($diff>0)
{
$totalUptime += $diff;
}
}

if ($timestamp>=$endTime)
{
break;
}

$lastTimestamp = $timestamp;
$lastWorking = $isWorking;
}

print "Total uptime: ".$totalUptime." seconds";

您只需要用您自己的数据库记录填充$data

关于PHP 计算 'downtime',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com