result - ideone
I changed% of% in minutes and in foreach at each iteration, the value of the $total
element also in minutes to perform the calculations with the same units.
$array = array('04:45', '01:30', '00:45');
$total = '07:00';
$explodeHoraTotal = explode(":",$total); //retorna um array onde cada elemento é separado por ":"
$minutosTotal = $explodeHoraTotal[0];
$minutosTotal = $minutosTotal*60;
$total =$minutosTotal+$explodeHoraTotal[1];
foreach ($array as $tem => $key) {
$quebraHora = explode(":",$key); //retorna um array onde cada elemento é separado por ":"
$minutos = $quebraHora[0];
$minutos = $minutos*60;
$tot =$minutos+$quebraHora[1];
$percentual = round(($tot / $total) * 100);
$percentual_total .= "Tempo: " . $key . ", Percentual: " . $percentual . "<br>";
}
echo $percentual_total;
Why did your script go wrong?
We must always keep in mind that we can only perform mathematical operations for the same quantity with numbers that represent exactly the same unit of measure. You were wanting to do a mathematical operation involving numbers with two units of measure, hour and minute. It could, yes, be transformed into decimal times, example, $key
result: (4,5hs/1,5hs)
In the code below I made the array in decimal times 3 períodos de 1,5hs
and total hours also $array = array('4.75', '1.5', '0.75');
- decimal times - example: 4 hours and 45 minutes, in decimals, are 4 hours and 3 quarters of an hour, that is 4.75
In this way we can do mathematical operations as follows:
$array = array('4.75', '1.5', '0.75');
$total = '7.0';
foreach ($array as $tem => $key) {
$percentual = round(($key / $total) * 100);
$percentual_total .= "Tempo: " . $key . ", Percentual: " . $percentual . "\n";
}
echo $percentual_total;
ideone result
Turning back the operations you were wanting to do, we have PHP simply ignored the part of the hours after the colon including the colon. Then $total = '7.0';
was transformed into 04:45
and 4
into '07:00'
.
Result 7
is exactly round((4 / 7) * 100);
view in ideone