第一个数组如下所示:
Array
(
[0] => Array
(
[employee_id] => 100
[year] => 2014
[month] => 7
[amount] => 16.00
[employee_name] => John
)
[1] => Array
(
[employee_id] => 100
[year] => 2014
[month] => 6
[amount] => 2.00
[employee_name] => John
)
[2] => Array
(
[employee_id] => 573
[year] => 2014
[month] => 7
[amount] => 10.00
[employee_name] => Bill
)
)
我想创建一个这样的数组:
Array
(
[0] => Array
(
[employee_id] => 100
[year] => 2014
[amount_month7] => 16.00
[amount_month6] => 2.00
[employee_name] => John
)
[1] => Array
(
[employee_id] => 573
[year] => 2014
[amount_month7] => 10.00
[amount_month6] => 0.00
[employee_name] => Bill
)
)
因此,每个月的金额总计为每个员工。
现在我确实成功地使用了很多ifs和elseifs,但我不知道用foreach语句做这个可能会更好,但是我找不到根据其他值对值进行求和的方法。 声明应该是
foreach
if (employee_id, year and month) is the same, amount_month[month] += amount
使用foreach有一种简单的方法吗?
答案 0 :(得分:0)
$values = array_unique(array_map(
function ($v) { return $v['employee_id']; },
$array
));
$result = array();
foreach ($values as $val) {
$result[] = array_filter($array, function ($v) use ($val) {
return $v['employee_id'] == $val;
});
}
答案 1 :(得分:0)
如果您通过PHP而不是通过SQL进行此重组,则可能更容易创建如下数组:
Array
(
[0] => Array
(
[employee_id] => 100
[year] => 2014
[amounts] => Array
(
[6] => 2.00
[7] => 16.00
)
[employee_name] => John
)
[1] => Array
(
[employee_id] => 573
[year] => 2014
[amounts] => Array
(
[7] => 10.00
)
[employee_name] => Bill
)
)