I have an associative array that is built from a MYSQL query result. It has 190 keys which are made up of 10 unique 'name' and 19 unique 'display_name' (2B, 3B, HR, RBI, HR etc), with each 'name' and 'display_name' combination having a 'value'.
array (size=190)
0 =>
array (size=3)
'name' => string 'Name 1' (length=17)
'display_name' => string '2B' (length=2)
'value' => string '10' (length=2)
1 =>
array (size=3)
'name' => string 'Name 2' (length=20)
'display_name' => string '2B' (length=2)
'value' => string '7' (length=1)
2 =>
array (size=3)
'name' => string 'Name 3' (length=18)
'display_name' => string '2B' (length=2)
'value' => string '5' (length=1)
3 =>
array (size=3)
'name' => string 'Name 4' (length=19)
'display_name' => string '2B' (length=2)
'value' => string '3' (length=1)
4 =>
array (size=3)
'name' => string 'Name 5' (length=11)
'display_name' => string '2B' (length=2)
'value' => string '4' (length=1)
I would like to build array that has the unique 'display_name' as keys along with the 'name' as a key and the 'value' associated with that. In other words, if you were visualize this as a table, currently it looks like:
name : display name : value
name1 2B 10
name2 2B 7
name3 2B 5
name4 2B 3
name5 2B 4
I would like it to look like:
name : 2B : 3B : RBI : HR
name1 10 5 7 10
name2 8 6 5 9
name3 9 4 3 5
name4 2 1 1 1
name5 6 2 2 8
I know I can do this in MYSQL but I would like to know the solution in PHP. I have tried many different things and referenced (among many others): Transposing multidimensional arrays in PHP
MYSQL similar solution: Transpose Rows to Headers in MYSQL
The closest that I can get to is this, but it does get me the unique 'display_name' values as keys, rather $fieldHash['display_name'] all 190 values.
while ($arr = mysql_fetch_assoc($res)){
$row [] = $arr;
foreach($row as $resultArray){
foreach ( $resultArray as $key=>$val ){
$fieldHash[$key][] = $val;
}
}
}
In this instance, I know the data model but in the future I would like to be dynamic for any number of 'display_name'.
If it's helpful, here is the MYSQL Query:
$query = "SELECT teaminfo.name, league_stat_categories.display_name, team_points_season.value
FROM team_points_season, teaminfo, league_stat_categories
WHERE team_points_season.league_key = '$league_key' AND team_points_season.team_key = teaminfo.team_key AND team_points_season.league_key = league_stat_categories.league_key
AND team_points_season.stat_id = league_stat_categories.stat_id
GROUP BY league_stat_categories.display_name, team_points_season.team_key";
Thanks for any help!