1

我有一个$department变量,它是一个Department类的实例。

该类Department有一个名为的属性$employees,其中包含与该部门相关的实例数组Employee(从数据库中检索)。

该类Employee有一个名为$salary_amountand的属性$job_type_id$employees数组元素按$job_type_id排序。

对于指定的部门,我正在输出该部门的员工列表,如下所示:

Employees for IT Department
----------------------------

<?php foreach($department->employees as $employee): ?>
  <?php echo $employee->name; ?>
  <?php echo $employee->salary_amount; ?>
<?php endforeach; ?>

什么是一种有效的操作方式,以便我可以 在员工列表旁边显示每个$department->employees 人的总和? $salary_amount $job_type_id

Employees for IT Department
----------------------------

## Help Desk ##

Joseph Lazar
$47,000

John Q. Smith
$15,444

--> Total Salary for Help Desk: $62,444


## Database Administrator ##

Piet Pietersen
$55,120

Ivan Horvat
$63,750

--> Total Salary for Help Desk: $118,870

当前方法

目前,$employees由单个 SQL 查询填充,按我想要的方式排序结果。然后,我运行一个单独的 SQL 查询,使用另一个问题的技术来$salary获取每个总和的数组。$job_type_id

但是,第二个查询的结果集存储在不同的变量$subtotals中。因此,我仍然存在有效地让 Sum-Total 与员工列表“在上下文中”显示的问题。

我碰巧正在使用Yii 框架,但这可能无关紧要,除非我应该从完全不同的角度考虑或处理这类问题?请在评论中告诉我。

更新 1

这是我正在使用的当前代码,但是感觉很混乱,并且可能有更好的方法。如上所述,聚合是由单独的 SQL 完成的,但是我愿意接受替代方案。

<?php 

$employee_key = 0;
$employees_count = sizeof($department->employees);

$type_sum_key = 0;
$current_type_in_focus = null;
$next_type_in_focus = null;

foreach($department->employees as $employee)
{
  $current_type_in_focus = $employee->job_type_id;
  $next_type_in_focus = (isset($department->employees[$employee_key+1])) ? $department->employees[$employee_key+1]->job_type_id : null;

  # output individual employee data
  echo $employee->name;
  echo $employee->salary_amount;

  # output aggregated total for job type
  if ( $current_type_in_focus !== $next_type_in_focus || $employee_key+1 == $employees_count )
  {
    echo '--> Total Salary for ' . $employee->jobType->name . ': ' . $department->subtotals[$type_sum_key]->total;
    $type_sum_key++; 
  }

  $income_key++;
}

?>
4

1 回答 1

0

一种方法是使用 while 循环。例如(为了清楚起见,以下代码示例不格式化输出,它还输出 job_type_id 而不是描述,因为问题中未显示该数据):

    $employees = $department->employees;
    $employee = current($employees);

    while($employee)
    {
        $job_type_id = $employee->job_type_id;
        $total_salary = 0;

        echo "## Job Type $job_type_id ##";

        while ($employee && $employee->job_type_id == $job_type_id)
        {
            echo $employee->name;
            echo $employee->salary_amount;
            $total_salary += $employee->salary_amount;
            $employee = next ($employees);
        }

        echo "-->Total Salary for Job Type $job_type_id: $total_salary";
    }
于 2012-07-11T23:12:56.263 回答