how to sum 2d array - php

Good evening
I have a question here. i have two arrays: $duration_c[$k][$s]. it prints all ok
$duration_c[0][0]="19:30:00";
$duration_c[0][1]="00:10:00";
$duration_c[1][0]="00:30:00";
$duration_c[1][1]="00:20:00";
than to sum
$times=$duration_c[$k][$s];
function sum_the_time($times) {
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
echo sum_the_time($times);
how to sum $duration_c[0][0]+$duration_c[0][1] and $duration_c[1][0]+$duration_c[1][1], and how to print?
there is error Invalid argument supplied for foreach()

you are sending only one value to sum_the_time function as $times=$duration_c[$k][$s];
$times has only one value you can print and check what value is going to the function by writing like this
$times=$duration_c[$k][$s];
echo $times;
use
$times=$duration_c[$k];
so that you can send array to your function and foreach will not give you error
$times=$duration_c[$k]; // contains array of times
function sum_the_time($times) {
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
echo sum_the_time($times);

This does it less in PHP code, and keeps the execution flow as much as possibly in the PHP runtime, written in C:
<?php
$duration_c[0][0]="19:30:00";
$duration_c[0][1]="00:10:00";
$duration_c[1][0]="00:30:00";
$duration_c[1][1]="00:20:00";
$sum = 0;
foreach($duration_c as $durations) {
$today = strtotime('today');
$sum += array_sum(array_map(function($str) use ($today) {
return strtotime($str)-$today;
}, $durations));
}
echo $sum; // 73800 seconds, that's 20.5 hours

$times=$duration_c[$k][$s]; should be $times=$duration_c[$k];, otherwise you are passing a single time to the function, not an array of times.

Related

Sum two centesimal times

I found this code but there is an error I can't found
function sum_time($tempo1, $tempo2) {
$times = array($tempo1, $tempo2);
$seconds = 0;
foreach ($times as $tempo)
{
list($hour, $minute, $second) = explode('.', $tempo);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d.%02d.%02d', $hours, $minutes, $seconds);
}
echo sum_time('3.0.00', '4.83.00');
the result is 08.23.00 instead of 7.83.00
Probably the problem is the code sums times in hh.mm.ss while I want to sum tims in hh.cc (hours.cents)
You can convert it to not use seconds but cents like this,
<?php
function sum_time($tempo1, $tempo2) {
$times = array($tempo1, $tempo2);
$hours = 0;
$cents = 0;
foreach ($times as $tempo)
{
list($hour, $cent) = explode('.', $tempo);
$hours += $hour;
$cents += $cent;
}
$hours += floor($cents / 100);
$cents = $cents % 100;
// return "{$hours}:{$cents}";
return sprintf('%02d.%02d', $hours, $cents);
}
echo sum_time('3.0', '4.83');

Get total amount of hours from 2 variables

Here is my code:
$time = "20:58:05";
$time2 = "10:40:00";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
echo $result;
The output of the above code is - 07:38:05
i want it to display like this - 31:38:05. How can i achieve this?
Convert both times to seconds, add them, and then calculate the hours, minutes, and seconds yourself.
$time = "20:58:05";
$time2 = "10:40:00";
$secs = strtotime($time)-strtotime("00:00:00");
$secs2 = strtotime($time2)-strtotime("00:00:00");
$total = $secs + $secs2;
$hours = floor($total/3600);
$mins = floor(($total % 3600) / 60);
$secs = $total % 60;
echo sprintf("%d:%02d:%02d", $hours, $mins, $secs);
The solution of Barmar works when adding hours that are below 24:00:00, but when you add 2 variable with each variable exceeds 24:00:00 it gives a wrong output. For example:
$time = "20:58:05";
$time2 = "30:40:00";
$secs = strtotime($time)-strtotime("00:00:00");
$secs2 = strtotime($time2)-strtotime("00:00:00");
$total = $secs + $secs2;
$hours = floor($total/3600);
$mins = floor(($total % 3600) / 60);
$secs = $total % 60;
echo sprintf("%d:%02d:%02d", $hours, $mins, $secs);
output of the above code: -431348:-2:-55
Here is a code that works even if the data of the variables exceeds 24:00:00:
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$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}";
}
i found this code here

How to sum two times with milliseconds?

Is there any way to sum two times with milliseconds like this:
00:01:02.73
00:03:03.01
to one?
the result should be like this:
00:04:05.74
format is simple "hours:minutes:seconds.milliseconds"
If yes, how?
well I wrote few functions which is helping me to do that
$time1 = "00:15:45.89";
$time2 = "00:18:30.22";
$milli1 = timeToMilliseconds($time1);
$milli2 = timeToMilliseconds($time2);
$new = $milli1 + $milli2;
$time = formatMilliseconds($new);
echo $time;
function timeToMilliseconds($time){
$time_start = substr($time, -11, -3);
$time_end = substr($time, -3);
$time_arr = explode(':', $time_start);
$seconds = 0;
foreach($time_arr as $key => $val){
if($key == 0){
$seconds += $val * 60 * 60;
}elseif($key == 1){
$seconds += $val * 60;
}elseif($key == 2){
$seconds += $val;
}
}
$seconds = $seconds.$time_end;
$milliseconds = $seconds * 1000;
return $milliseconds;
}
function formatMilliseconds($milliseconds) {
$seconds = floor($milliseconds / 1000);
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$milliseconds = $milliseconds % 1000;
$seconds = $seconds % 60;
$minutes = $minutes % 60;
$format = '%u:%02u:%02u.%03u';
$time = sprintf($format, $hours, $minutes, $seconds, $milliseconds);
return rtrim($time, '0');
}
Has a problem with your solution #Scorpioniz, when the time is "1:34:55.831" for example, the return from formatMilliseconds is "1582:10:31.704".
I made some changes in the timeToMilliseconds function and I think that is more consistent:
function timeToMilliseconds($time){
$dateTime = new DateTime($time);
$seconds = 0;
$seconds += $dateTime->format('H') * 3600;
$seconds += $dateTime->format('i') * 60;
$seconds += $dateTime->format('s');
$seconds = floatval($seconds . '.' . $dateTime->format('u'));
return $seconds * 1000;
}
Or if your version of PHP is minor than 5.2.2 then you can do:
function timeToMilliseconds($time){
sscanf($time, "%d:%d:%d.%d", $hours, $minutes, $seconds, $microseconds);
$seconds += $hours * 3600;
$seconds += $minutes * 60;
$seconds = floatval($seconds . '.' . $microseconds);
return $seconds * 1000;
}
I hope someone enjoy.
(Sorry for my English if I said something strange :P)
I've found this, it has less code than yours and it does the job. I've added function for milliseconds.
I'm wondering if php has something built-in for this.
/**
* #author Masino Sinaga, http://www.openscriptsolution.com
* #copyright October 13, 2009
*/
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
$Imiliseconds = 0.0;
foreach ($times as $time){
list($rest, $miliseconds) = explode('.', $time);
$Imiliseconds += '0.'.$miliseconds;
list($hour, $minute, $second) = explode(':', $rest);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$seconds += floor($Imiliseconds);
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
$miliseconds = $Imiliseconds-floor($Imiliseconds);
// return "{$hours}:{$minutes}:{$seconds}:{$miliseconds}";
return sprintf('%02d:%02d:%02d:%02d', $hours, $minutes, $seconds, $miliseconds); // Thanks to Patrick
}
echo sum_the_time($time, $time2); // this will give you a result: 19:12:25

PHP: Pass Array to Function with 2 acceptable variable only

How can i pass the value in my array to a function that can only accept 2 variable.
function i created
function sum_the_time($time1,$time2){
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time) {
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
when i try to display it gives me the total time:
here how i display the result.
echo sum_the_time('01:45:22', '17:27:03');
where i declared the time.
i want to pass the stored value in my array
here's what i did
$stored_time = array();
for($i=0;$i<count($lang_val);$i++){
$target_time = $project_time;
$stored_time[] = $target_time;
}
this will add a value to my array[].
the time is get from the generated script.
i just want to know how can i pass the value of my array. to the function i created.
sometimes there are 3 value in my array or my 5 or so on.
Rewrite the function and make it accept an array instead.
function sum_the_time($times){
$seconds = 0;
foreach ($times as $time) {
//...
pass $times array directly to the function sum_the_time() as
$times = array($time1, $time2);
function sum_the_time($times)
{
if (count($times) > 0)
{
// your code
}
}

adding two time values of similar formats using php

i have two time values as give below
$time = 06:58:00;
$time2 = 00:40:00;
I am doing this for calculating the appointments and available time for a particular user
so i tried in this way
$max_date=abs(strtotime($time) + strtotime($time2));
but it is returning $max_date =2673452280
any suggestions pls
this code sample would take hour in $time and add the hour in $time2 to it
for example: time=06:58:00, time2=00:40:00, result = 07:38:00
$time = "06:58:00";
$time2 = "00:40:00";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
Use this function...
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$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}";
}
strtotime function takes full-date as an argument and valid format are as following:
http://www.php.net/manual/en/datetime.formats.php
You can see that in online PHP manual for the function at http://php.net/manual/en/function.strtotime.php
If you're build those time strings from a database before, you'd probably want to rebuild them to something like this:
$time = "00:06:58";
$time2 = "40 minutes";
$timestamp = strtotime($time." +".$time2);
$endTime = date("d.m.Y H:i:s", $timestamp);
Easiest way to add two times using php is :
1) Convert time from H:i:s (e.g. 08:15:40) format to seconds.
2) do the same for second time value ref:step 1
3) add converted values and store it php variable
4) Now convert total (which is in seconds) to H:i:s
and it works for me.
PHP Script:
$str_time ="08:04:40";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_old_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$str_time ="02:10:22";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_toadd_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$hrs_old_int1 = $hrs_old_seconds + $hrs_toadd_seconds;
echo $Total=gmdate("H:i:s", $hrs_old_int1);
Result= :10:15:02
Anudeep's solution was great for my use case, but I needed to be able to add negative times as well. Here's a slightly edited version of his code to take and return negative time strings ("-01:01:01" for example):
public static function sum_the_times($time1, $time2)
{
$times = array($time1, $time2);
$seconds = 0;
$negative = false;
foreach ($times as $time) {
list($hour,$minute,$second) = explode(':', $time);
if(substr($hour,0,1) == '-'){
$seconds -= substr($hour,1)*3600;
$seconds -= $minute*60;
$seconds -= $second;
} else {
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
}
if (substr($seconds, 0, 1) == '-') {
$negative = true;
$seconds = ($seconds * -1);
}
$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 ($negative ? "-" : "")."{$hours}:{$minutes}:{$seconds}";
}
You can try this
$time = "04:00:00";
$time2 = "03:30:00";
$result = date("H:i:s",strtotime($time)+strtotime($time2));
echo $result;
It gives output 07:30:00 but it does not work sometime in different version of operating system. If you want to get sum of time then you can use this code
<?php
function CalculateTime($time1, $time2) {
$time1 = date('H:i:s',strtotime($time1));
$time2 = date('H:i:s',strtotime($time2));
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$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}";
}
$time1= '23:32:05';
$time2 = '01:29';
echo CalculateTime($time1,$time2);
?>
In the second code, you can send time in hour:minutes or hours:minutes:seconds. This code accept both format because it convert time automatically
Here's a version that will cater for over 24 hours and doesn't use strtotime:
$time0 = "24:01:02";
$time1 = "01:02:03";
$matches0 = explode(':',$time0); // split up the string
$matches1 = explode(':',$time1);
$sec0 = $matches0[0]*60*60+$matches0[1]*60+$matches0[2];
$sec1 = $sec0+ $matches1[0]*3600+$matches1[1]*60+$matches1[2]; // get total seconds
$h = intval(($sec1)/3600);
$m = intval(($sec1-$h*3600)/60);
$s = $sec1-$h*3600-$m*60;
echo $str = str_pad($h, 2, '0', STR_PAD_LEFT).':'.str_pad($m, 2, '0', STR_PAD_LEFT).':'.str_pad($s, 2, '0', STR_PAD_LEFT);

Categories