我的数组总和有问题。所以我有这个数组:
Array
(
[0] => Array
(
[totalGames] => 21
[nature] => 542
)
[1] => Array
(
[totalGames] => 2
[nature] => 418
)
[2] => Array
(
[totalGames] => 26
[nature] => 728
)
[3] => Array
(
[totalGames] => 3
[nature] => 542
)
[4] => Array
(
[totalGames] => 2
[nature] => 418
)
)
我想对此数组求和以获得此结果:
Array
(
[0] => Array
(
[totalGames] => 24
[nature] => 542
)
[1] => Array
(
[totalGames] => 4
[nature] => 418
)
[2] => Array
(
[totalGames] => 26
[nature] => 728
)
)
我试过这样:
while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC))
{
if($aData['nature'] == $aRecord['nature']){
$aData[] = $aRecord;
}else{
$aData['nature'] = $aRecord['nature'];
$aData['totalGames'] += $aRecord['nature']['totalGames'];
}
}
但不行。我做错了什么?你能帮我吗 ? Thx提前和抱歉我的英语。
我也试过但是没有用:
SELECT COUNT(*) as totalGames, nature FROM master WHERE date(date)="2015-11-20" GROUP BY nature ORDER by totalGames
答案 0 :(得分:2)
您的代码应为:
$myArr = array(array('totalGames' => 21, 'nature' => 542),array('totalGames' => 2,'nature' => 418),array('totalGames' => 26,'nature' => 728), array('totalGames' => 3,'nature' => 542),array('totalGames' => 2,'nature' => 418));
$sum = array_reduce($myArr, function ($a, $b) {
isset($a[$b['nature']]) ? $a[$b['nature']]['totalGames'] += $b['totalGames'] : $a[$b['nature']] = $b;
return $a;
});
print_r($sum);
答案 1 :(得分:-1)
尝试
while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC)){
$hash = $aRecord['nature'];
if(isset($aData[$hash])){
$aData[$hash]['totalGames'] += $aRecord['totalGames'];
}else{
$aData[$hash]['nature'] = $aRecord['nature'];
$aData[$hash]['totalGames'] = $aRecord['totalGames'];
}
}