I have an array of objects defined similarly to the below:
$scores = array(); // Bob round 1 $s = new RoundScore(); $s->Round_Name = 'Round 1'; $s->Player_Name = 'Bob'; $s->Score = 10; $scores[0] = $s; // Bob round 2 $s = new RoundScore(); $s->Round_Name = 'Round 2'; $s->Player_Name = 'Bob'; $s->Score = 7; $scores[1] = $s; // Jack round 1 $s = new RoundScore(); $s->Round_Name = 'Round 1'; $s->Player_Name = 'Jack'; $s->Score = 6; $scores[2] = $s; // Jack round 2 $s = new RoundScore(); $s->Round_Name = 'Round 2'; $s->Player_Name = 'Jack'; $s->Score = 12; $scores[3] = $s;
If I loop through and dump the $scores object into a table, it will look something like this:
Round_Name Player Score ---------------------------- Round 1 Bob 10 Round 2 Bob 7 Round 1 Jack 6 Round 2 Jack 12
What I want, however, is something like this:
Player Round 1 Round 2 Total ------------------------------- Bob 10 7 17 Jack 6 12 18
I’m not going to know in advance how many rounds or players there’ll be and let’s just say I can’t change the way the objects are constructed.
What’s the most efficient way to do this in php?
If we can assume that:
Then, what we can do is print each player’s score as we moved through the array while calculating the total in the process but resetting it if we see a new player:
Sample output:
This should be quite efficient because it only goes through the array once.