我有一個$department
變量,它是Department
類的一個實例。彙總數組並顯示彙總結果旁邊的細節
Department
類有一個名爲$employees
的屬性,其中包含與該部門相關的Employee
實例的數組(從數據庫中檢索)。
Employee
類有一個屬性,稱爲$salary_amount
和$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查詢填充,訂購我多麼希望的結果。然後,我使用another question中的一項技術運行單獨的SQL查詢,以獲得每個$job_type_id
的總計$salary
的數組。
但是,第二個查詢的結果集存儲在另一個變量$subtotals
中。因此,我仍然存在高效地讓Sum-Total顯示與僱員名單「in-context」的問題。
我碰巧在使用Yii framework,但是這可能是不相關的,除非我應該從完全不同的角度思考或處理這類問題。請在評論中告訴我。
更新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++;
}
?>
你就不能在一個初始化的變量'0'並在循環數據時執行'$ var + = $ employee-> salary_amount'?然後最後你會得到你想要的數額。附:你應該多付約翰·Q·史密斯,如果他看到了這一點,他就會青睞 - 那些像Q這樣的中間初始值得肯定的人應該更多:-D – DaveRandom 2012-07-11 21:35:08
@DaveRandom是的,我也這麼認爲。可憐的bug子手。我正在採用'foreach'循環的方法,但是當試圖找到同一個'$ job_type_id'結束和下一個開始的組時,它似乎很笨拙,因此我可以輸出中間的總數。我試圖使用一堆'if語句',但代碼變得很難看,並且不能正常工作..所以我希望有更好的方法。 – Turgs 2012-07-11 22:22:24
我正在想辦法用SQL'GROUP BY'完成整個工作,但我想不出任何本身沒什麼問題的東西。我會告訴你想我可以想到,如果你喜歡,雖然... – DaveRandom 2012-07-11 22:31:14