Daniel P.
Daniel P.

Reputation: 184

PHP Sum multi-dimentional array date interval, for an employee clock

time is DateTime Object formatted as:

$time = $date->format("%H:%i:%s");

I'm trying to sum hours and group employees.

I have:

Array
(
    [0] => Array
        (
            [employee] => 2
            [time] => 00:0:17
        )

    [1] => Array
        (
            [employee] => 1
            [time] => 00:0:4
        )

    [2] => Array
        (
            [employee] => 2
            [time] => 02:0:0
        )

    [3] => Array
        (
            [employee] => 3
            [time] => 02:0:0
        )

    [4] => Array
        (
            [employee] => 3
            [time] => 01:0:0
        )

)

And I need something like, grouped and sum:

Array
(
    [0] => Array
        (
            [employee] => 2
            [totalTime] => 02:0:17
        )

    [1] => Array
        (
            [employee] => 1
            [totalTime] => 00:0:4
        )

    [2] => Array
        (
            [employee] => 3
            [totalTime] => 03:0:0
        )

)

Any thoughts? Maybe convert time to UNIX and manipulate from there?

Upvotes: 1

Views: 68

Answers (1)

Xorifelse
Xorifelse

Reputation: 7911

Since you want something like like the desired output, perhaps this will do:

foreach($array as $value){
  if(!isset($data[$value['employee']])){
    $data[$value['employee']] = 0;
  }

  $parsed = date_parse($value['time']);
  $data[$value['employee']] += $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
}

print_r($data);

Instead of creating a multidimensional array, $data will have the key of the employee and the value of the total time in seconds.

Obviously you can convert seconds very easily to a format if you so please.

Upvotes: 1

Related Questions