Skip to content
Advertisement

Push data to a parent array from within child array (PHP)

I have an array of baseball teams and within each is an array of that team’s seasons. Within each season is the number of wins in that season. I would like to tally up all of a team’s wins and then have this number pushed into the data about each team. My end goal is to then sort this master array by the total number of wins each team has.

My problem is, I can’t figure out how to push the totalGamesWon tally up to the main array of team data.

Apologies in advance for the inefficient coding! If there’s a better way for a newbie like me to do this, I’m all ears!

$teams = array(
  array (
    'teamName' => 'Yankees',
    'seasons' => array (
      array(
        'seasonName' => '2018 Regular Season',
        'wins' => 100
      ),
      array(
        'seasonName' => '2018 Playoffs',
        'wins' => 2
      )
    )
  ),
  array (
    'teamName' => 'Red Sox',
    'seasons' => array (
      array(
        'seasonName' => '2018 Regular Season',
        'wins' => 108
      ),
      array(
        'seasonName' => '2018 Playoffs',
        'wins' => 11
      )
    )
  ),
);

foreach ($teams as $team) {
  $totalGamesWon = 0;
  foreach ($team['seasons'] as $season) {
    $totalGamesWon += $season['wins'];
  }
  $team['totalGamesWon'] = $totalGamesWon;
}

echo $teams[0]['teamName'];       // outputs "Yankees"
echo $teams[0]['totalGamesWon'];  // should output "102". Instead, I get "Notice: Undefined index: totalGamesWon"

Advertisement

Answer

Just change $team to &$team so you pass the $team by reference instead of by value:

foreach ($teams as &$team) {
   $totalGamesWon = 0;
   foreach ($team['seasons'] as $season) {
       $totalGamesWon += $season['wins'];
   }
   $team['totalGamesWon'] = $totalGamesWon;
}

By default ($team) it is passed by value which means it is only changed within the scope (in the loop). So each iteration the value of $team[‘totalGameswon’] is set but the actual array $teams is not affected.

When it’s passed by reference the current item that is changed ($team['totalGamesWon']) is changing the value in the actual array.


so: (passed by value)

foreach ($teams as $key => $team) {
   $totalGamesWon = 0;
   foreach ($team['seasons'] as $season) {
       $totalGamesWon += $season['wins'];
   }
   $teams[$key]['totalGamesWon'] = $totalGamesWon;
}

and (passed by reference)

foreach ($teams as &$team) {
   $totalGamesWon = 0;
   foreach ($team['seasons'] as $season) {
       $totalGamesWon += $season['wins'];
   }
   $team['totalGamesWon'] = $totalGamesWon;
}

would give you the same result.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement