I have an array variable, I store all the time in this array. I want to total all the stored value in my array. I tried using a for loop but it can't read the time format.
I'm using CakePHP
In my usercontroller:
$this->set('project_time',$sele_lang['time']);
I used that code to get the estimated time for each project. i don't have any problem with this.
then in my php to get set time i created a variable and array to stor the time.
$target_time and $stored_time=array()
if(i have two projects) //i assume that i have two project
for($i = 0; $i < count($lang_val); $i++)
{
$target_time = $project_time; // this will get the estimated time
$stored_time[] = $target_time; //this will store the time in array.
$tempo = date("H:i:s", strtotime($stored_time[$i])); //this will get the first array value.
}
I'm stacked here.
I don't know if there's something a function that can sum all the time stored in my array. or I'm thinking that if i stored the first value to a temp file then add the temp value to a the second value of the array that would give me the result i want but it a time based i only tried that to a integer.
thanks for advance. sorry for the lack of information in my first post.
Something like this? Your code doesn't make sense, this is my best interpretation. (And it's a bad way of doing it. We can merge the second loop in the first one.
for($i=0;$i<count($lang_val);$i++){
$target_time = $project_time;
$stored_time[] = $target_time; //Assuming this is a timestamp
}
$intTotalTime = 0;
foreach($stored_time as $intTimeStamp) {
$intTotalTime += $intTimeStamp;
}
echo "Total Time: ". date("H:i:s", strtotime($intTotalTime));
Why would you like to get the sum of timestamps? The result would be a very odd number.
I assume the $lang_val is an array with timestamps.
$new = array();
foreach( $lang_val as $entry ) {
$new[] = strtotime( $entry );
}
// Debugging
var_dump( $new );
// Actual value
var_dump( array_sum($new) );
Or
$total = 0;
foreach( $lang_val as $entry ) {
$total += strtotime( $entry );
}
After your comment:
$data = array(
'00:15:00',
'01:05:05',
'10:00:15'
);
$total = 0;
foreach( $data as $timestamp ) {
// Get values or set default if not present.
list( $hours, $minutes, $seconds ) = explode( ':', $data ) + array(
0 => 0,
1 => 0,
2 => 0
);
// Convert to seconds
$hours = $hours * 3600;
$minutes = $minutes * 60;
$total += $hours + $minutes + $seconds;
}
var_dump( $total );
You can use array_reduce
and strtotime
:
<?php
$array = array('00:10:15', '02:00:00', '05:30:00');
// Get total amount of seconds
$seconds = array_reduce($array, function($carry, $timestamp) {
return $carry + strtotime('1970-01-01 ' . $timestamp);
}, 0);
// Get hours
$hours = floor($seconds/ 3600);
$seconds -= $hours * 3600;
// Get minutes
$minutes = floor($seconds/ 60);
$seconds -= $minutes * 60;
// Convert to timestamp
$timestamp = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
var_dump($timestamp); //string(8) "07:40:15"