0

I have an array like following and inside it 2 arrays that have a value and want to know how to get the sum of both hours for example 01:00 + 04:00 = 05:00

Array:

Array
(
    [0] => stdClass Object
        (
            [total_time] => 01:00
        }
    [1] => stdClass Object
        (
            [total_time] => 04:00
        }
}

thank you.

2 Answers2

0

There would be a lot of different ways to achieve this. I prefer to use array_map to get the values out of the object and convert the values. The it should be easy enough for array_sum to sum it all together.

$hours_array = array_map("get_hours", $array);
$results = array_sum($hours_array);

function get_hours($object) {
    // Check values first

    // For just hours.
    list($hours,) = explode(":", $object->{'total_time'});

    return $hours;
}
adrianp
  • 320
  • 2
  • 9
0

Follow this steps:

  • loop over array;
  • convert HH:MM format to seconds like this;
  • sum all converted seconds;
  • convert summed seconds back to HH:MM format like this.
Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107