按键值对数组排序,然后获得数组中的5个最高和最低值

时间:2018-07-12 06:20:34

标签: php arrays sorting multidimensional-array

我有一个名为“ 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 ) 
)

我有一个函数可以通过“ holders”值对该数组进行排序:

function compareHolders($a, $b) {

    $aPoints < $a['holders'];
    $bPoints < $b['holders'];

    return strcmp($aPoints, $bPoints);

}

我遍历另一个数组来创建此数组:

foreach ($players as $player) {
    $player['name'] = $athlete['name'];
    $player['holders'] = $total_result_yesterday;
    $playersArray[] = $player;
}

我正在尝试按“ holder”值对数组进行排序:

usort($playersArray, 'compareHolders');

print_r($playersArray);

最后,我试图在新排序的数组中获得5个最高和5个最低的“ holder”值:

$first_5_players = array_slice($playersArray, 0, 5, true);
$last_5_players = array_slice($playersArray, -5);

但是,排序无法正常进行。到期值未按期望的顺序显示。如何使排序正常工作?谢谢!

2 个答案:

答案 0 :(得分:3)

您的排序功能compareHolders不正确。 $aPoints$bPoints未定义。由于holders键的值是数字,因此可以使用比较运算符。尝试执行以下操作:

function compareHolders($a, $b) {
    if ($a['holders'] == $b['holders']) {
        // return 0 if equal
        return 0;
    }
    return ($a['holders'] > $b['holders']) ? -1 : 1;
}

答案 1 :(得分:0)

您实际上并没有比较// create instance of dialog AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // get inflater and inflate layour for dialogue LayoutInflater inflater = this.getLayoutInflater(); View dialogView = inflater.inflate(R.layout.alert_label_editor, null); // now set layout to dialog dialogBuilder.setView(dialogView); // create instance like this OR directly mentioned in layout Button button= (Button) dialogView.findViewById(R.id.label_field); button.setText("test label"); AlertDialog alertDialog = dialogBuilder.create(); // show dialog alertDialog.show(); 中的两个值,因为您没有声明compareHolders()$aPpoints

这应该有效:

$bPoints

或者您也可以返回:

function compareHolders($a, $b) {

    $aPoints = $a['holders'];
    $bPoints = $b['holders'];

    return strcmp($aPoints, $bPoints);

}

然后,您可以摆脱return strcmp($a['holders'], $b['holders']); ,因为您没有比较字符串。