I am attempting to convert an associative array to a 2D array to allow me to export it to Google Sheets. I’ve figured out a simplistic solution that works as follows:
$headers = $data["resultSets"][0]["headers"]; $rowSet0 = $data["resultSets"][0]["rowSet"][0]; $rowSet1 = $data["resultSets"][0]["rowSet"][1]; $hackresults = array_map(null, $headers, $rowSet0, $rowSet1);
This produces the following:
( [0] => Array ( [0] => SEASON_ID [1] => 22017 [2] => 22017 ) [1] => Array ( [0] => Player_ID [1] => 203954 [2] => 203954 ) [2] => Array ( [0] => Game_ID [1] => 0021701118 [2] => 0021701105 ) [3] => Array ( [0] => GAME_DATE [1] => MAR 28, 2018 [2] => MAR 26, 2018 ) [4] => Array ( [0] => MATCHUP [1] => PHI vs. NYK [2] => PHI vs. DEN ) [5] => Array ( [0] => WL [1] => W [2] => W ) [6] => Array ( [0] => MIN [1] => 9 [2] => 27 ) [7] => Array ( [0] => FGM [1] => 2 [2] => 6 ) [8] => Array ( [0] => FGA [1] => 6 [2] => 12 ) [9] => Array ( [0] => FG_PCT [1] => 0.333 [2] => 0.5 ) [10] => Array ( [0] => FG3M [1] => 0 [2] => 0 ) [11] => Array ( [0] => FG3A [1] => 1 [2] => 1 ) [12] => Array ( [0] => FG3_PCT [1] => 0 [2] => 0 ) [13] => Array ( [0] => FTM [1] => 1 [2] => 8 ) [14] => Array ( [0] => FTA [1] => 2 [2] => 10 ) [15] => Array ( [0] => FT_PCT [1] => 0.5 [2] => 0.8 ) [16] => Array ( [0] => OREB [1] => 2 [2] => 1 ) [17] => Array ( [0] => DREB [1] => 1 [2] => 12 ) [18] => Array ( [0] => REB [1] => 3 [2] => 13 ) [19] => Array ( [0] => AST [1] => 0 [2] => 2 ) [20] => Array ( [0] => STL [1] => 0 [2] => 1 ) [21] => Array ( [0] => BLK [1] => 0 [2] => 2 ) [22] => Array ( [0] => TOV [1] => 1 [2] => 4 ) [23] => Array ( [0] => PF [1] => 1 [2] => 5 ) [24] => Array ( [0] => PTS [1] => 5 [2] => 20 ) [25] => Array ( [0] => PLUS_MINUS [1] => 7 [2] => 20 ) [26] => Array ( [0] => VIDEO_AVAILABLE [1] => 1 [2] => 1 ) )
This is the output I’m looking for, but there are 27 “rowSet”s, and it seems there must be a recursive way of performing this task.
I’ve looked at a number of custom array_map_recursive style functions but haven’t had any success. Apologies and thanks in advance, I am a terrible novice coder!
Advertisement
Answer
You can use argument unpacking.
With the ...
operator, you can use all the elements under $data["resultSets"][0]["rowSet"]
as additional arguments to array_map
.
$headers = $data["resultSets"][0]["headers"]; $rowSets = $data["resultSets"][0]["rowSet"]; $results = array_map(null, $headers, ...$rowSets);
(This isn’t recursion, but I think it does what you’re trying to do.)