PHP:获取数组中不同日期的总和

时间:2019-07-10 05:48:01

标签: php arrays loops datetime

你好,我只是一个初学者,但是我现在正在构建一个应用程序,该应用程序可以获取总的工作时间。

这里我有一个 time_start 数组,客户进入该阈值的阈值与 time_end

的阈值相同

此人登录的地方是日志

            $time_start = [
                [0] => '22:00:00',
                [1] => '03:00:00',
                ];
            $time_end = [
                [0] => '02:00:00',
                [1] => '08:00:00',
                ];
            $logs = [
                [0] => '2019-07-09 22:00:00',
                [1] => '2019-07-10 02:00:00',
                [2] => '2019-07-10 03:00:00',
                [3] => '2019-07-10 08:00:00',
            ];

所以我想获取他们夜班时间的总和,日期不同。

我正在尝试获取它:

            foreach( $logs as $check_time ){

                $attendance_date_time = date("Y-m-d",strtotime($check_time));
                $time_starts = date('Y-m-d H:i:s', strtotime("$attendance_date_time $time_start"));
                $time_ends = date('Y-m-d H:i:s', strtotime("$attendance_date_time $time_end"));
                if ( $check_time >= $time_starts && $check_time <= $time_ends )
                {
                    $time[] = $check_time;
                }else{
                    $time = null
                }

            }

应该获取所有日志,因为它介于time_start和time_end之间,并将其存储到$ time

加总我得到的时间。

由于我是php的新手,所以获得总工作时间是他们最简单的主意吗?因为我得到的null是因为它的time_end是签入的日期。

2 个答案:

答案 0 :(得分:1)

这是您的摘录,

$time_start = [
    0 => '22:00:00',
    1 => '03:00:00',
];
$time_end = [
    0 => '02:00:00',
    1 => '08:00:00',
];
$logs = [
    0 => '2019-07-09 22:00:00',
    1 => '2019-07-10 02:00:00',
    2 => '2019-07-10 03:00:00',
    3 => '2019-07-10 08:00:00',
];
$time = [];
$diff = 0;
for ($j = 0; $j < count($logs); $j = $j + 2) {
    $attendance_start = date("Y-m-d", strtotime($logs[$j]));
    $attendance_end   = date("Y-m-d", strtotime($logs[$j + 1]));
    for ($i = 0; $i < count($time_start); $i++) {
        $time_starts = date('Y-m-d H:i:s', strtotime("$attendance_start " . $time_start[$i] . ""));
        $time_ends   = date('Y-m-d H:i:s', strtotime("$attendance_end " . $time_end[$i] . ""));
        if ($logs[$j] >= $time_starts && $logs[$j + 1] <= $time_ends) {
            array_push($time, $logs[$j], $logs[$j + 1]);
            // calculating diff for two alternate days
            $diff += (round((strtotime($logs[$j + 1]) - strtotime($logs[$j])) / 3600, 1));
            break;
        }
    }
}
echo $diff . " Hours";die;

Demo

输出:-

9 Hours

答案 1 :(得分:0)

for循环是最简单的方法

$time_start = [
  '22:00:00',
  '03:00:00',
];
$time_end = [
  '02:00:00',
  '08:00:00',
];
$logs = [
  '2019-07-09 22:00:00',
  '2019-07-10 02:00:00',
  '2019-07-10 03:00:00',
  '2019-07-10 08:00:00',
];

$totalDiff = 0;

for($i =0 ; $i < count($logs); $i = $i + 2)
{
  $startDate = strtotime($logs[$i]);
  $endDate = strtotime($logs[$i+1]);

  $diff = $endDate-$startDate;

  $totalDiff += $diff;
}

$hourDiff = $totalDiff / 3600;
echo $hourDiff . ' hours';

Demo