I am trying to divide an array based on values within the array, and to sort it based on keys that the array also has. My array currently looks like this:
array:6 [▼
"player_ids" => array:8 [▼
0 => "103"
1 => "221"
2 => "283"
3 => "321"
4 => "333"
5 => "406"
6 => "425"
7 => "428"
]
"game_id" => array:8 [▼
103 => "33058041"
221 => "33058041"
283 => "33058041"
321 => "33058041"
333 => "33058041"
406 => "33058041"
425 => "33058041"
428 => "33058041"
]
"goals" => array:8 [▼
103 => "0"
221 => "0"
283 => "0"
321 => "0"
333 => "0"
406 => "0"
425 => "0"
428 => "0"
]
"assists" => array:8 [▼
103 => "0"
221 => "0"
283 => "0"
321 => "0"
333 => "0"
406 => "0"
425 => "0"
428 => "0"
]
"yellows" => array:8 [▼
103 => "0"
221 => "0"
283 => "0"
321 => "0"
333 => "0"
406 => "0"
425 => "0"
428 => "0"
]
"red" => array:8 [▼
103 => "0"
221 => "0"
283 => "0"
321 => "0"
333 => "0"
406 => "0"
425 => "0"
428 => "0"
]
]
with arrays with each of the players embedded in a particular field. How would I manipulate this array to make it so that player_ids
would become the first key, like so:
"103" => array:6 [▼
player_ids => "103"
game_id => "33058041"
goals => "0"
assists => "0"
yellows => "0"
red => "0"
]
for each of the player id's listed?
you can loop through the player_ids
key in your big array and create a new array with the structure you want. Something like this.
$newArray = array();
foreach ($array['player_ids'] as $p){
$newArray[$p] = array (
'player_ids' => $p,
'game_id' => $array['game_id'][$p],
'goals' => $array['goals'][$p],
'assists' => $array['assists'][$p],
'yellows' => $array['yellows'][$p],
'red' => $array['red'][$p]
)
}
EDIT: As I'm posting this, it's really just a slightly different way to do what @Long Kim already posted, although his is a bit more elegant for this scenario. I'd go with that... The method below is better for a larger array though.
You don't provide a name for your 'master array', so I'm calling it $masterArray here. $newArray is what I believe you're looking for.
$newArray = array();
foreach($masterArray['player_ids'] as $playerid){
foreach($masterArray as $key => $value){
if($key=="player_ids"){
$newArray[$playerid][$key] = $playerid;
}
else{
$newArray[$playerid][$key] = $value[$playerid];
}
}
}