PHP Sum多维数组值,其中某些索引相同 [英] PHP Sum multidimensional array values where certain index is the same
问题描述
这里只是一个简单的问题.我有以下数组:
just a simple problem here. I have the following array:
Array(21) {
[0] => Array(7) {
["punti"] => Integer 418
["vittorie"] => Integer 9
["podi"] => Integer 18
["gv"] => Integer 14
["id_pilota"] => Integer 1
["team"] => String(15) "Red Bull Racing"
["naz"] => String(2) "it"
}
[1] => Array(7) {
["punti"] => Integer 353
["vittorie"] => Integer 6
["podi"] => Integer 16
["gv"] => Integer 3
["id_pilota"] => Integer 19
["team"] => String(16) "Scuderia Ferrari"
["naz"] => String(2) "it"
}
[2] => Array(7) {
["punti"] => Integer 335
["vittorie"] => Integer 4
["podi"] => Integer 15
["gv"] => Integer 1
["id_pilota"] => Integer 5
["team"] => String(12) "Mercedes-AMG"
["naz"] => String(2) "it"
}
[3] => Array(7) {
["punti"] => Integer 181
["vittorie"] => Integer 1
["podi"] => Integer 5
["gv"] => Integer 1
["id_pilota"] => Integer 2
["team"] => String(12) "Mercedes-AMG"
["naz"] => String(2) "it"
}
[4] => Array(7) {
["punti"] => Integer 147
["vittorie"] => Integer 0
["podi"] => Integer 3
["gv"] => Integer 0
["id_pilota"] => Integer 14
["team"] => String(15) "Racing Point F1"
["naz"] => String(2) "mx"
}
[5] => Array(7) {
["punti"] => Integer 127
["vittorie"] => Integer 0
["podi"] => Integer 0
["gv"] => Integer 0
["id_pilota"] => Integer 13
["team"] => String(7) "Haas F1"
["naz"] => String(2) "dk"
}
下降到21个元素.
我的目标是根据每个飞行员的团队来汇总所有要点("punti"指数). 因此,要获得如下内容:
My goal is to sum up all the points ("punti" indexes), based on each pilot's team. So to obtain something like this:
Array(10) {
[0] => Array(2) {
["team"] => String(...) "Mercedes-AMG")
["points"] => Integer 516
我知道这很容易,但是解决这种问题的最快/最方便的方法是什么?
I know this is quite easy, but what is the quickest / most convenient way to solve such problem?
推荐答案
您需要遍历结果,遇到新团队时在输出中添加新条目,或者在找到同一团队时更新积分值再次.最简单的方法是,首先根据小组名称为输出建立索引,然后使用array_values
重新对数组进行数字索引:
You need to iterate over your results, adding a new entry to the output when you encounter a new team, or updating the points value when you find the same team again. This is most easily done by initially indexing the output by the team name, and then using array_values
to re-index the array numerically:
$teams = array();
foreach ($results as $result) {
$team = $result['team'];
if (!isset($teams[$team])) {
$teams[$team] = array('team' => $team, 'points' => $result['punti']);
}
else {
$teams[$team]['points'] += $result['punti'];
}
}
$teams = array_values($teams);
print_r($teams);
输出(用于您的示例数据):
Output (for your sample data):
Array
(
[0] => Array
(
[team] => Red Bull Racing
[points] => 418
)
[1] => Array
(
[team] => Scuderia Ferrari
[points] => 353
)
[2] => Array
(
[team] => Mercedes-AMG
[points] => 516
)
[3] => Array
(
[team] => Racing Point F1
[points] => 147
)
[4] => Array
(
[team] => Haas F1
[points] => 127
)
)
这篇关于PHP Sum多维数组值,其中某些索引相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!