我需要调查已经运行和待机的机器长度。我在数据库中有条目如下:
move $t4, $t2
时间现在是| machine | running | start |
|---------|---------|---------------------|
| 1 | 0 | 2018-03-13 00:00:00 |
| 1 | 1 | 2018-03-13 00:30:00 |
| 1 | 0 | 2018-03-13 02:00:00 |
。使用上面的示例时,结果应为2018-03-13 04:00:00
(正在运行)和01:30:00
(待机)。
进行此类计算的最佳方法是什么?我的数据库条目是否足够好?
我在后端使用像Laravel这样的工具,并且f.ex. Vue和Moment.js在前端。提前谢谢。
答案 0 :(得分:0)
希望这可以解决问题:
<?php
$rs = [
[
'machine' => 1,
'running' => 0,
'start' => '2018-03-13 00:00:00'
],
[
'machine' => 1,
'running' => 1,
'start' => '2018-03-13 00:30:00'
],
[
'machine' => 1,
'running' => 0,
'start' => '2018-03-13 02:00:00'
],
[
'machine' => 1,
'running' => 1,
'start' => '2018-03-13 03:00:00'
],
];
$lastState = -1;
$startDateTime = $endDateTime = null;
$totalStates = count($rs);
foreach ($rs as $r)
{
$machine = $r['machine'];
$running = $r['running'];
$start = $r['start'];
if (-1 === $lastState) {
$startDateTime = new \DateTime($start);
$lastState = $running;
}
else {
$endDateTime = new \DateTime($start);
$dateTimeInterval = $endDateTime->diff($startDateTime);
echo "State: ". $lastState ." / Total time: " . $dateTimeInterval->format("%H:%I:%S") . "\n";
$startDateTime = new \DateTime($start);
$lastState = $running;
}
}
输出:
State: 0 / Total time: 00:30:00
State: 1 / Total time: 01:30:00
State: 0 / Total time: 01:00:00