我需要创建一个代码,它将接受$time1的值并减去$time2的值,然后取$time3的值并减去$time4的值,等等,直到$time记录用完为止。它应该保持一个运行的总数。
模拟数据:
$time[1] = "2017-08-28 18:30:00";
$time[2] = "2017-08-28 14:00:00";
$time[3] = "2017-08-28 13:00:00";
$time[4] = "2017-08-28 12:45:00";
$time[5] = "2017-08-28 12:30:00";
$time[6] = "2017-08-28 12:00:00";例如:1-2=4.5h,3-4=0.25小时,5-6=0.5h;total=5.25小时.
$hourdiff = round((strtotime($time[1]) - strtotime($time[2]))/3600, 1); //gives you the quantity of hours worked between 2 records我需要一种方法来选择记录1和2,计算$hourdiff,将其添加到正在运行的总数中,然后选择records 3和4,计算$hourdiff,将其添加到正在运行的总计,等等,直到没有剩下的记录需要计算。
发布于 2017-08-31 02:51:43
听起来像是在寻找一个for循环:
for ($i = 1; $i <= count($time) - 1; $i++) {
$hourdiff = round((strtotime($time[$i + 1]) - strtotime($time[$i]))/3600, 1);
echo "The difference is: $hourdiff" . "<br />";
}这将反映出时间上的五个差异。
请注意,您需要从1开始使用$i,因为您不能从第一个事件中减去“nothing”!要解决这一问题,您需要在计数不足1的情况下停止索引。
这可以看到正在工作的这里。
希望这会有帮助!)
发布于 2017-08-31 02:50:35
迭代数组,但不是将1添加到迭代变量中,而是添加两个(并检查超出界限的错误):
<?php
$time[0] = "2017-08-28 18:30:00";
$time[1] = "2017-08-28 14:00:00";
$time[2] = "2017-08-28 13:00:00";
$time[3] = "2017-08-28 12:45:00";
$time[4] = "2017-08-28 12:30:00";
$time[5] = "2017-08-28 12:00:00";
$total = 0;
for ($i = 0; $i < count($time); $i += 2) {
if ($i + 1 > count($time) - 1) break; // check of out of bounds
$total += round((strtotime($time[$i]) - strtotime($time[$i + 1]))/3600, 1); // add diff of next two numbers
}
echo $total;发布于 2017-08-31 03:43:00
试着:
$time[1] = "2017-08-28 18:30:00";
$time[2] = "2017-08-28 14:00:00";
$time[3] = "2017-08-28 13:00:00";
$time[4] = "2017-08-28 12:45:00";
$time[5] = "2017-08-28 12:30:00";
$time[6] = "2017-08-28 12:00:00";
$times = array();
$total = 0;
foreach ($time as $n => $t0) {
if ($n % 2) {
continue;
}
$t1 = strtotime($time[$n - 1]);
$t2 = strtotime($t0);
$k = sprintf('%s-%s', $n - 1, $n);
$diff = ($t1 - $t2) / 3600;
$times[$k] = sprintf('%.2f hours', $diff);
$total += $diff;
}
print_r($times);
printf('TOTAL : %s hours', $total);输出
Array
(
[1-2] => 4.50 hours
[3-4] => 0.25 hours
[5-6] => 0.50 hours
)
TOTAL : 5.25 hours 或者yo可以尝试使用日期::diff
$time[1] = "2017-08-28 18:30:00";
$time[2] = "2017-08-28 14:00:00";
$time[3] = "2017-08-28 13:00:00";
$time[4] = "2017-08-28 12:45:00";
$time[5] = "2017-08-28 12:30:00";
$time[6] = "2017-08-28 12:00:00";
$times = array();
$total = new DateTime;
foreach ($time as $n => $t0) {
if ($n % 2) {
continue;
}
$t1 = new DateTime($time[$n - 1]);
$t2 = new DateTime($t0);
$k = sprintf('%s-%s', $n - 1, $n);
$diff = $t1->diff($t2);
$times[$k] = $diff->format('%h hour(s) %i min(s) %s sec(s)');
$total = $total->add($diff);
}
$total = ($total->diff(new DateTime))->format('%h hour(s) %i min(s) %s sec(s)');
print_r($times);
printf('TOTAL : %s', $total);输出
Array
(
[1-2] => 4 hour(s) 30 min(s) 0 sec(s)
[3-4] => 0 hour(s) 15 min(s) 0 sec(s)
[5-6] => 0 hour(s) 30 min(s) 0 sec(s)
)
TOTAL : 5 hour(s) 15 min(s) 0 sec(s) https://stackoverflow.com/questions/45972420
复制相似问题