0

我有一组 intime 和 outtime,我想计算 intime 和 outtime 之间的持续时间并添加所有持续时间以获得总持续时间。
例子:

Array
    (
    [1] => Array
        (
            ['intime'] => 1342086993
            ['outime'] => 1342087585
        )

    [3] => Array
        (
            ['intime'] => 1342087669
            ['outtime] => 1342096165
        )

    [5] => Array
        (
            ['intime'] => 1342096339
            ['outime'] => 1342096345
        )
    )

$total_duration = 0;
foreach($logArray as $log)
{
  $duration = $log['outime'] - $log['intime'];
  $total_duration += $duration;
}

$duration_hrs = $total_duration/3600;
echo 'Time spend in hrs :'.$duration_hrs;

但这并没有给我适当的持续时间。有没有其他方法可以做到这一点。

4

4 回答 4

2

使用array_map首先将每个元素映射到持续时间,然后使用 array_sum对它们求和:

$durations = array_map(function ($e) {
  return $e['outtime'] - $e['intime'];
}, $logArray);
$total_duration = array_sum($durations);
于 2012-07-13T11:05:25.350 回答
0
$total_duration = 0;
foreach($logArray as $log)
{
  $duraton = $log['outtime'] - $log['intime'];
  $total_duration += $duration;
}
$duration_hrs = $total_duration/3600;
echo 'Time spend in hrs :'.$duration_hrs;
于 2012-07-13T11:03:20.250 回答
0

您的无语法脚本对我来说很好:

<?php

    $logArray = Array (
        1 => Array (
            'intime' => 1342086993,
            'outime' => 1342087585
        ),
        3 => Array (
            'intime' => 1342087669,
            'outime' => 1342096165
        ),
        5 => Array (
            'intime' => 1342096339,
            'outime' => 1342096345
        )
    );

    $total_duration = 0;
    foreach( $logArray as $log ) {
      $duration = $log[ 'outime' ] - $log[ 'intime' ];
      $total_duration += $duration;
        echo $duration / 3600 . "<br />";
    }

    $duration_hrs = $total_duration / 3600;
    echo 'Time spend in hrs: ' . $duration_hrs;

?>

和输出:

0.16444444444444
2.36
0.0016666666666667
Time spend in hrs: 2.5261111111111 

似乎您的时间格式不正确:13, July 2012 04:04:32 PM应该13. July 2012 04:04:32 PM

strtotime('13. July 2012 04:04:32 PM')

正确工作。它应该给1342195472而不是你1342168834。因此,请检查生成错误微时间的时间格式

于 2012-07-13T11:18:12.550 回答
0

您的代码中有一个简单的错字。检查:

duraton vs duration

改变,会好的。

于 2012-07-13T12:44:46.540 回答