我需要帮助来总结某些条件下的数组值
我想计算每个用户的调用总和,我尝试这样,但它显示所有查询的总和[用户]
$array_out_ = array();
$usercalls = $usertalk = $userpause = $userwait = $userdispo = $userdead = 0;
foreach ($queryusers2 as $user) {
$current_user = $user['user'];
$usercalls += $user['calls'];
$usertalk += $user['talk'];
$userpause += $user['pause'];
$userwait += $user['wait'];
$userdispo += $user['dispo'];
$userdead += $user['dead'];
$array_out_[$current_user]['calls'] = $usercalls;
$array_out_[$current_user]['talk'] = $usertalk;
$array_out_[$current_user]['pause'] = $userpause;
$array_out_[$current_user]['wait'] = $userwait;
$array_out_[$current_user]['dispo'] = $userdispo;
$array_out_[$current_user]['dead'] = $userdead;
}
此方法返回$ usercalls(代理29的305)和(代理117的436) 但是我想要305代理商29和代理商117只有131
由于
答案 0 :(得分:4)
我建议您将查询SQL更改为类似的内容,您可以在其中对数据进行分组和汇总。
SELECT
tn.user,
SUM(tn.calls) AS usercalls,
SUM(tn.talk) AS usertalk,
SUM(tn.pause) AS userpause,
SUM(tn.wait) AS userwait,
SUM(tn.dispo) AS userdispo,
SUM(tn.dead) AS userdead
FROM tablename tn
GROUP BY tn.user
这将返回你需要的东西:
agent29, 305, ...
agent117, 436, ...
答案 1 :(得分:1)
您的值$usercalls
,$usertalk
,...未重新初始化。并为所有用户累积。您的代码仅适用于第一个用户,仅因为您的列表是由用户订购的。
你可以初始化一个数组并直接在其中求和:
$array_out_ = array();
foreach ($queryusers2 as $user)
{
$current_user = $user['user'];
if (!isset($array_out_[$current_user])) {
$array_out_[$current_user] = [
'calls' => 0, 'talk' => 0, 'pause' => 0, 'wait' => 0,
'dispo' => 0, 'dead' => 0
];
}
$array_out_[$current_user]['calls'] += $user['calls'];
$array_out_[$current_user]['talk'] += $user['talk'];
$array_out_[$current_user]['pause'] += $user['pause'];
$array_out_[$current_user]['wait'] += $user['wait'];
$array_out_[$current_user]['dispo'] += $user['dispo'];
$array_out_[$current_user]['dead'] += $user['dead'];
}