添加小数PHP foreach循环

时间:2014-10-07 23:49:04

标签: php loops sum counter nested-loops

我一直坚持这一点并寻求帮助。我相信我需要添加一个额外的循环或计数器,我只是不知道何时何地:)

我正在尝试为每位员工完成现金,CC和总计的小计。

foreach ($weekly as $week){
        $week_array = getStartAndEndDate($week['week'],$week['year']);
        if(isset($week['employeeid'])){
                echo "<TR>";
                if($week['employeeid']!=$tmpEmp){
                        echo "<TD colspan='5'><strong>".$week['employeeid']."</strong></TD></TR>
                        <TR><TD>".$week_array['week_start']."</TD>";
                        $tmpEmp = $week['employeeid'];
                }
                else {
                        echo "<TD>".$week_array['week_start']."</TD>";
                        $tmpEmp = $week['employeeid'];
                }      
                echo
                "<TD>".$week['CC']."</TD>
                <TD>".$week['Cash']."</TD>
                <TD>".$week['total']."</TD>
                <TD><a href=employee.php?week=".$week['week']."&year=".$week['year'].">Report</a></TD>
                </TR>";


                $tmpCC += $week['CC'];
                $tmpCash += $week['Cash'];
                $tmpTotal += $week['total'];


        }      

}
                echo "<TR><TD><strong>Group Total</strong></TD>
                <TD>".$tmpCC."</TD>
                <TD>".$tmpCash."</TD>
                <TD>".$tmpTotal."</TD>
                <TD></TD>
                </TR>
                 </TABLE><HR />";

---当前结果---

Employee        CC      Cash    Total   View Report
1
2014-10-20      0.00    271.61  271.61  Report
2
2014-10-06      75.38   0.00    75.38   Report
2014-10-13      0.00    472.66  472.66  Report
4
2014-09-29      219.39  0.00    219.39  Report
5
2014-09-29      0.00    464.40  464.40  Report
2014-10-20      390.37  0.00    390.37  Report
Group Total     685.14  1208.67 1893.81

---想要结果---

Employee        CC      Cash    Total   View Report
1
2014-10-20      0.00    271.61  271.61  Report
Subtotal        XX      XX      XX     
2
2014-10-06      75.38   0.00    75.38   Report
2014-10-13      0.00    472.66  472.66  Report
Subtotal        XX      XX      XX
4
2014-09-29      219.39  0.00    219.39  Report
Subtotal        XX      XX      XX
5
2014-09-29      0.00    464.40  464.40  Report
2014-10-20      390.37  0.00    390.37  Report
Subtotal        XX      XX      XX
Group Total     685.14  1208.67 1893.81

1 个答案:

答案 0 :(得分:2)

类似于跨循环持有员工ID的方式,您可以保持运行总计。

在你的循环之上:

$tmpSubTotal = 0;

$tmpTotal += $week['total'];之后:

$tmpSubTotal += $week['total'];

if语句:

if($week['employeeid']!=$tmpEmp){
    if($tmpEmp) {
        echo '<td colspan="3"></td><td>' . $tmpSubTotal . '</td><td></td></tr><tr>';
        $tmpSubTotal = 0;
    }

    echo "<TD colspan='5'><strong>".$week['employeeid']."</strong></TD></TR>
    <TR><TD>".$week_array['week_start']."</TD>";
    $tmpEmp = $week['employeeid'];
}