我需要计算警卫的总工作时数。我能够让每个班次的总时数,但我不知道如何将它们加在一起。我有一个用户表,一个signIn表和一个Shift表。这是我到目前为止所得到的。
在控制器中:
$signIns = $em->getRepository('AppBundle:SignIn')
->findAllThisMonthDesc();
foreach ($signIns as $signIn) {
$diff[$signIn->getId()]['signInId'] = $signIn->getId();
$diff[$signIn->getId()]['shiftId'] = $signIn->getShift();
$diff[$signIn->getId()]['workerId'] = $signIn->getWorker();
$diff[$signIn->getId()]['hoursWorked'] = date_diff($signIn->getSignedInAt(), $signIn->getSignedOutAt() );
}
return$this->render('users/show.html.twig', [
'user' => $user,
'memos' => $memos,
'loggedInUser' => $loggedInUser,
'phoneScreenings' => $phoneScreenings,
'sites' => $sites,
'signIns' => $signIns,
'diff' => $diff,
]);
树枝模板:
{% for signIn in signIns %}
{% for dif in diff %}
{% if signIn.worker.id == user.id and signIn.shift.id == dif.shiftId.id and dif.workerId.id == user.id %}
{{ dif.hoursWorked.h }}hrs, {{ dif.hoursWorked.i }} mins -
{% endif %}
{% endfor %}
{% endfor %}
我的输出是9小时和2分钟 - 12小时和43分钟。但我想将它加在一起,以便显示21小时,44分钟
答案 0 :(得分:4)
为什么不在Controller中进行计算,然后将值发送给Twig呢?虽然在Twig中,您可以简单地创建一个变量,然后将9小时,2分钟和12小时,43分钟添加到变量中。但这可能有些复杂,因为如果你有9小时,45小时和12小时,50分钟呢?你必须再做一些(43分钟+50分钟)的转换,然后再进行几小时的转换,虽然可以实现,但这可能是一项非常重要的工作。
<?php
$signIns = $em->getRepository('AppBundle:SignIn')
->findAllThisMonthDesc();
foreach ($signIns as $signIn) {
$diff[$signIn->getId()]['signInId'] = $signIn->getId();
$diff[$signIn->getId()]['shiftId'] = $signIn->getShift();
$diff[$signIn->getId()]['workerId'] = $signIn->getWorker();
$diff[$signIn->getId()]['hoursWorked'] = date_diff($signIn->getSignedInAt(), $signIn->getSignedOutAt() );
}
$hours = 0;
$minutes = 0;
$extraHours = 0;
foreach ($signIns as $signIn) {
foreach($diff as $dif){
if($signIn['workerId'] == $user['id'] && $signIn['shiftId'] == $dif['shiftId'] && $dif['workerId'] == $user['id'] ){
$hours += $dif['hoursWorked']['h'];
$minutes += $dif['hoursWorked']['i'];
}
}
}
if($minutes >= 60){
$extraHours = intval( $minutes/60 );
$minutes = $minutes%60;
}
$realTotal = ($hours + $extraHours) . "hrs, " . $minutes . "mins";
return$this->render('users/show.html.twig', [
'user' => $user,
'memos' => $memos,
'loggedInUser' => $loggedInUser,
'phoneScreenings' => $phoneScreenings,
'sites' => $sites,
'signIns' => $signIns,
'diff' => $diff,
'realTotal' => $realTotal,
]);
// IN TWIG YOU CAN DO JUST...
{{ realTotal }}
答案 1 :(得分:0)
您必须在控制器中计算它:
$totalHours = new \DateTime('00:00:00');
foreach ($signIns as $signIn) {
foreach($diff as $dif){
if($signIn['workderId'] == $user['id'] && $signIn['shiftId'] == $dif['shiftId'] && $dif['workerId'] == $user['id'] ){
$totalHours = self::addtime($totalHours, $dif['hoursWorked']);
}
}
}
并使用此功能:
public function addtime($time1,$time2)
{
$interval1 = $time1->diff(new \DateTime('00:00:00')) ;
$interval2 = $time2->diff(new \DateTime('00:00:00')) ;
$e = new \DateTime('00:00');
$f = clone $e;
$e->add($interval1);
$e->add($interval2);
$total = $f->diff($e)->format("%H:%I:%S");
return new \DateTime($total);
}