In this website I’ve found a function to convert seconds in an human readable format, like this:
3 weeks, 2 days, 1 hour, 27 minutes, 52 seconds
I want to translate it in italian, so I just translated array keys. The function now is this
function secondsToHumanReadable($secs) {
$units = array(
'settimane' => 604800,
'giorni' => 86400,
'ore' => 3600,
'minuti' => 60,
'secondi' => 1
);
foreach ( $units as &$unit ) {
$quot = intval($secs / $unit);
$secs -= $quot * $unit;
$unit = $quot;
}
return $units;
}
It works pretty well, but there’s a little problem: in english all the plurals ends with one letter less, but unfortunately in italian it’s not the same, as you can see below.
English Italian
- weeks, week - settimane, settimana
- days, day - giorni, giorno
- hours, hour - ore, ora
- minutes, minute - minuti, minuto
- seconds, second - secondi, secondo
I want to find a solution to print singular keys when the values are == 1.
I was thinking that I could merge the array with another array that have singular keys, using array_combine().
$singular_units = array(
'settimana',
'giorno',
'ora',
'minuto',
'secondo'
);
print_r(array_combine( $singular_units, $units ));
/* print_r:
Array
(
[settimana] => 604800
[giorno] => 86400
[ora] => 3600
[minuto] => 60
[secondo] => 1
)
*/
The array above is what I need, but I’m not able to use it, since I just cannot use another foreach.
$seconds = 12345*60; // just an example
$units = secondsToHumanReadable($seconds);
$time_string = '';
foreach ($units as $u => $v)
if (!empty($v))
$time_string.= $v.' '.$u.', ';
echo substr($time_string, 0, -2);
// 1 settimane, 1 giorni, 13 ore, 45 minuti
// this echo is not correct :( is expected to be like this:
// 1 settimana, 1 giorno, 13 ore, 45 minuti
How could I implement the singular words?
Any help is really appreciated! Thank you so much in advance!
You can implement them any way you like, IMHO preferably something not like the current solution which lacks clarity and readability (at least that’s how the local-var-mutation-with-refs-and-variable-ping-pong looks like to me).
Just one possible solution:
See it in action.