PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 28, 2022

[FIXED] Sum all key/value pairs within a multidimensional PHP array

 February 28, 2022     arrays, laravel, multidimensional-array, php     No comments   

Issue

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!


Solution

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;
      }
  }
}


Answered By - Chun
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing