Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function calculate_hours ($array)
- {
- $time1 = "";
- $time2 = "00:00:00";
- $time1_seconds = 0;
- $time2_seconds = 0;
- $sum_hours = 0;
- $sum_mins = 0;
- $sum_secs = 0;
- $is_negative = false;
- $type = "";
- sscanf($time2, "%d:%d:%d", $hours2, $minutes2, $seconds2);
- $time2_seconds = isset($seconds2)
- ? $hours2 * 3600 + $minutes2 * 60 + $seconds2
- : $hours2 * 60 + $minutes2;
- foreach ($array as $time):
- $type = key($time);
- $time1 = $time[$type] . ":00";
- sscanf($time1, "%d:%d:%d", $hours1, $minutes1, $seconds1);
- $time1_seconds = isset($seconds1)
- ? $hours1 * 3600 + $minutes1 * 60 + $seconds1
- : $hours1 * 60 + $minutes1;
- $time2_seconds = ($type === "+")
- ? ($time1_seconds + $time2_seconds)
- : ($time2_seconds - $time1_seconds);
- endforeach;
- $is_negative = ($time2_seconds < 0)
- ? true
- : false;
- $sum_hours = ($is_negative === true)
- ? ceil($time2_seconds / 3600)
- : floor($time2_seconds / 3600);
- $sum_mins = ($is_negative === true)
- ? ceil($time2_seconds / 60 % 60)
- : floor($time2_seconds / 60 % 60);
- $sum_secs = ($is_negative === true)
- ? ceil($time2_seconds % 60)
- : floor($time2_seconds % 60);
- $sum_hours = str_pad(abs($sum_hours), 2, "0", STR_PAD_LEFT);
- $sum_mins = str_pad(abs($sum_mins), 2, "0", STR_PAD_LEFT);
- $sum_secs = str_pad(abs($sum_secs), 2, "0", STR_PAD_LEFT);
- $time2 = ($is_negative)
- ? "-{$sum_hours}:{$sum_mins}"
- : "+{$sum_hours}:{$sum_mins}";
- return $time2;
- }
- echo calculate_hours (array
- (
- array
- (
- "+" => "10:00"
- ),
- array
- (
- "-" => "05:45"
- ),
- array
- (
- "+" => "00:01"
- ),
- ));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement