[英]Sort array by key value and then get 5 highest and lowest values in array
I have an array called "playersArray" that looks like this: 我有一个名为“ playersArray”的数组,如下所示:
Array (
[0] => Array ( [name] => Joe [holders] => 0 )
[1] => Array ( [name] => Bob [holders] => 100 )
[2] => Array ( [name] => Jake [holders] => 100 )
[3] => Array ( [name] => Mike [holders] => 100 )
[4] => Array ( [name] => Tim [holders] => -0.0145 )
[5] => Array ( [name] => Frank[holders] => 100 )
[6] => Array ( [name] => Scott [holders] => 0.0583 )
[7] => Array ( [name] => Doug[holders] => 0.1308 )
[8] => Array ( [name] => Tommy [holders] => 0.2516 )
[9] => Array ( [name] => Eric [holders] => 100 )
)
I have a function to sort this array by the "holders" value: 我有一个函数可以通过“ holders”值对该数组进行排序:
function compareHolders($a, $b) {
$aPoints < $a['holders'];
$bPoints < $b['holders'];
return strcmp($aPoints, $bPoints);
}
I loop through another array to create this array: 我遍历另一个数组来创建此数组:
foreach ($players as $player) {
$player['name'] = $athlete['name'];
$player['holders'] = $total_result_yesterday;
$playersArray[] = $player;
}
I am trying to sort the array by "holder" value: 我试图按“ holder”值对数组进行排序:
usort($playersArray, 'compareHolders');
print_r($playersArray);
Finally, I am trying to get the 5 highest and 5 lowest "holder" values in the newly sorted array: 最后,我试图在新排序的数组中获得5个最高和5个最低的“ holder”值:
$first_5_players = array_slice($playersArray, 0, 5, true);
$last_5_players = array_slice($playersArray, -5);
However, the sorting is not working correctly. 但是,排序不能正常工作。 The values due not show in sequential order as desired.
到期值未按期望的顺序显示。 How can I get the sorting to work correctly?
如何使排序正常工作? Thank you!
谢谢!
your sorting function compareHolders
is not correct. 您的排序功能
compareHolders
不正确。 $aPoints
and $bPoints
are not defined. $aPoints
和$bPoints
未定义。 Since values for holders
key are numeric you can use the comparision operators. 由于
holders
键的值是数字,因此可以使用比较运算符。 Try doing following: 尝试执行以下操作:
function compareHolders($a, $b) {
if ($a['holders'] == $b['holders']) {
// return 0 if equal
return 0;
}
return ($a['holders'] > $b['holders']) ? -1 : 1;
}
You are not actually comparing the two values in compareHolders()
, because you're not declaring $aPpoints
and $bPoints
. 您实际上并没有在
compareHolders()
比较这两个值,因为您没有在声明$aPpoints
和$bPoints
。
This should work: 这应该工作:
function compareHolders($a, $b) {
$aPoints = $a['holders'];
$bPoints = $b['holders'];
return strcmp($aPoints, $bPoints);
}
or alternatively you could just return: 或者您也可以返回:
return strcmp($a['holders'], $b['holders']);
And then you could get rid of the strcmp()
, since you're not comparing strings. 然后您可以摆脱
strcmp()
,因为您没有比较字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.