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"
}
which goes down to 21 elements.
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?
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:Output (for your sample data):
Demo on 3v4l.org