简体   繁体   English

PHP总和foreach循环结果

[英]PHP sum foreach loop results

I have this foreach code, and I want to sum the values that it returns, can someone help me with that please? 我有这个foreach代码,我想对它返回的值求和,有人可以帮我吗?

foreach($timel->results() as $timel) {

       $timeDiff = strtotime($timel->end_date) - strtotime($timel->start_date);

       $hours = floor($timeDiff / 3600);
       $remainder = $timeDiff - $hours * 3600;
       $formattedTime = sprintf('%02d', $hours) . gmdate(':i:s', $remainder);
       echo $formattedTime, '<br>'; 
}

This code outputs: 此代码输出:

00:17:20 00:17:20

00:00:06 00:00:06

00:00:02 00:00:02

And I want to sum those value and then output 00:17:28. 我想对这些值求和,然后输出00:17:28。

you can use something like: 您可以使用类似:

<?php

$totaltime = 0;    

foreach($timel->results() as $timel) {

   $timeDiff = strtotime($timel->end_date) - strtotime($timel->start_date);

   $totaltime += $timeDiff;
 }

$hours = floor($totaltime / 3600);
$remainder = $totaltime - $hours * 3600;
$formattedTime = sprintf('%02d', $hours) . gmdate(':i:s', $remainder);

echo $formattedTime;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM