Sorting 2 arrays to get the highest in one and lowest in another
I have 2 arrays. The keys represent the player id in a game (and is the same i开发者_JAVA技巧n both arrays) and the value represents the Ping in one and the score in the other. What I am trying to do is get the Player ID (key) that has the highest ping and the lowest score. I can't get my head around any of the sorts that would do this.
I don't have to use 2 arrays, I just don't know how else to do it.
Thanks.
LIVE Demo: http://codepad.org/46m3mHIH
Arranging this type of architecture would work better...
$players = array(
array(
"name" => "l337 H4x0r",
"score" => 10432,
"ping" => 0.35
),
array(
"name" => "El Kabooom",
"score" => 19918,
"ping" => 0.45
),
array(
"name" => "Kapop",
"score" => 10432,
"ping" => 0.38
)
);
Then you could more efficiently sort your multi-dimensional array, and retrieve your $lowestScore
and $highestPing
values.
$playersScore = subval_sort($players,'score');
$lowestScore = $playersScore[0]['score'];
$playersPing = subval_sort($players,'ping');
$HighestPing = $playersPing[ count($players)-1 ]['score'];
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val){
$c[] = $a[$key];
}
return $c;
}
A bit unclear whether you're looking for two separate sorts, or 1 combined. If separate then the asort() function will sort based on the values while maintaining the correct key=>value association. Just use this against each array.
精彩评论