result - ideone
I transformed $total
in minutes and in the foreach at each iteration, the value of the element $key
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;
Because your script went wrong?
We should always keep in mind that we can only perform mathematical operations for the same quantity with numbers representing exactly the same unit of measure. You were looking for a mathematical operation involving numbers with two units of measurement, hour and minutes. It could, if it turned into decimal hours, example, (4,5hs/1,5hs)
outworking: 3 períodos de 1,5hs
In the code below I transformed the array into decimal hours $array = array('4.75', '1.5', '0.75');
and the total hours as well $total = '7.0';
- decimal hours - example: 4 hours and 45 minutes, in decimals, are 4 hours and 3 quarters of an hour, ie 4.75
That way we can do mathematical operations as can be seen below:
$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
Going back to the operations you were wanting to do, we have that PHP simply ignored the hours after the two points including the two points. So 04:45
turned into 4
and '07:00'
in 7
.
Upshot round((4 / 7) * 100);
is exactly 57
see in ideone
percentage of what? no one guesses here, and if Voce did in excel, it differs little from doing in php or any other language, the process is pretty much the same.
– Armando Marques Sobrinho
Of each hour of the array, you did not see in the question title?
– Eduardo Santos
I saw @Eduardo Santos, but, see, 67,857... and the 5-hour percentage? 1 hour? , it was kind of groundless your question, and it was like I said, from excel pro php eh a hop of nothing, if Voce Jah has there, Voce could tell us what would be your difficulty in php?
– Armando Marques Sobrinho
Not that that’s the answer to your question, but I think if you just want the percentage, it would be easier to convert everything to minutes
– Victor Eyer
I’ll edit the question with what I’m trying to do.
– Eduardo Santos
It gave to understand the purpose. The question that was badly formulated. :)
– Sam