-3

How do i get the sum of an multidimensional array?

Return of my Array:

array(25) {
  [0]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "01:30:00"
  }
  [1]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "00:30:00"
  }
 [2]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "00:30:00"
  }
  [3]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "00:15:00"
  }
  [4]=>
  array(1) {
    ["time_in_minutes"]=>
    string(8) "00:15:00"
  }

How do i get the sum of those values dynamicly? The expected output should be a Variable which adds all those time strings together

Qirel
  • 25,449
  • 7
  • 45
  • 62
  • 2
    Try: [`array_reduce()`](https://www.php.net/manual/en/function.array-reduce.php) – Jordi Nebot Mar 29 '19 at 08:43
  • What if the number of hours exceed 24 hours? Should days be introduced like `1 day, 10:15:00`, or should it say `34:15:00`? – Qirel Mar 29 '19 at 08:47
  • it should say 34:15:00 – Louis Michel Mar 29 '19 at 08:47
  • 2
    It's not just a simple sum here, it's a sum of time durations. This question isn't perfect but I don't think it's a proper duplicate. – Jeto Mar 29 '19 at 09:01
  • 2
    I agree with @Jeto. Also, it's unfair that 2 votes for marking as duplicate and you may now need 5 votes for reopening. `Type` of user doesn't matter here(since it has `Community`). – nice_dev Mar 29 '19 at 09:10
  • To sum times there is also a question https://stackoverflow.com/q/22681725/9811969 – Nik Mar 29 '19 at 09:20

1 Answers1

0

Best way is to convert time in seconds and then add them and again convert them into readable format. Like below:

function sum_the_time($times) {
    $seconds = 0;
    foreach ($times as $time) {
        list($hour, $minute, $second) = explode(':', $time['time_in_minutes']);
        $seconds += $hour*3600;
        $seconds += $minute*60;
        $seconds += $second;
    }

    $hours = floor($seconds/3600);
    $seconds -= $hours*3600;
    $minutes  = floor($seconds/60);
    $seconds -= $minutes*60;
    if ($seconds < 9) {
        $seconds = "0" . $seconds;
    }
    if ($minutes < 9) {
        $minutes = "0" . $minutes;
    }
    if($hours < 9) {
        $hours = "0" . $hours;
    }
    return "{$hours}:{$minutes}:{$seconds}";
}

In above example, $time is an array.

Nik
  • 2,885
  • 2
  • 25
  • 25
Chintan Trivedi
  • 207
  • 1
  • 5
  • $times is the Array right? so i pass the array through this function. Unfortunatly ill get an error at the explode function "Warning: explode() expects parameter 2 to be string, array given..." - What do i do wrong? – Louis Michel Mar 29 '19 at 08:54
  • My friend, it's just an example code for you, as I used it in my code so I pasted it as it is, for your case, you have to input values to explode, which suits you. I guess at explode, you should pass $time['time_in_minutes'] – Chintan Trivedi Mar 29 '19 at 08:57
  • Did it work ? if not please mail me. or dm me. – Chintan Trivedi Mar 29 '19 at 09:05