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!

JavaScript

Advertisement

Answer

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

JavaScript

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)

JavaScript

and (passed by reference)

JavaScript

would give you the same result.

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