以下是我的数组。我需要根据每个emp_firstname添加其Sum字段。有些只有一次到来,有些只有两次到来。我们如何求和该字段并使数组唯一?
Array
(
[0] => Array
(
[emp_firstname] => Alistair
[non_pm] => AMZ
[sum] => 2
)
[1] => Array
(
[emp_firstname] => Shakkeer
[non_pm] => SHK
[sum] => 3
)
[2] => Array
(
[emp_firstname] => Waqas
[non_pm] => WAS
[sum] => 12
)
[3] => Array
(
[emp_firstname] => Zain
[non_pm] => ZAI
[sum] => 9
)
[4] => Array
(
[emp_firstname] => Shakkeer
[gud_pmeditor] => SHK
[sum] => 4
)
[5] => Array
(
[emp_firstname] => Zain
[gud_pmeditor] => ZAI
[sum] => 2
)
)
答案 0 :(得分:1)
您可以使用这种方法获得所需的结果
$res=[];
foreach($arr as $val){
if(array_key_exists($val['emp_firstname'], $res))
$res[$val['emp_firstname']]['sum'] = ($res[$val['emp_firstname']]['sum'] + $val['sum']);
else
$res[$val['emp_firstname']] = $val;
}