1

I am developing a small application that pulls recent game data for players, and I want to display a total amount of the stats (goals, assists, plusminus, shots, pim) across all of the games by each player id.

This is an example of what my array looks like for three games that were pulled. The top level is the game id, followed by the player id's that were involved in that game. The layer under each player id are the stats that I want to total up in my output.

Test

I have attempted to loop through each game and player with the following code, but it only appears to pull the non-totaled stats from the first game.

foreach ($results as $result) {
  foreach ($result as $index => $value) {
    $sumArray[$index] = (isset($sumArray[$index]) ? $sumArray[$index] + $value : $value);
  }
}

Would anyone be able offer some guidance on how I can loop through and total up the player stats for each player id occurrence? Any help would be appreciated. Thank you!

2
  • Does this answer your question? php array recursive sum Commented Feb 23, 2022 at 1:34
  • 1
    Please never provide screenshots of dd() output when presenting array input data. var_export() output text is the most portal/usable for contributors. Your question doesn't express the exact desired result either. Do you merely want to append "total" elements as new elements on every parent array or do you want a separate array entirely? Commented Nov 14, 2023 at 5:39

1 Answer 1

1

I try to use a more readable variable name

foreach ($results as $game) {
  foreach ($game as $player => $performance) {
    if ( !isset($sumArray[$player] ) {
      $sumArray[$player] = $performance;
    } else {
      foreach ( $performance as $type => $value) {
        $sumArray[$player][$type] += $value;
      }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.