排序多维数组从高到低在php



25你好,我在这里检查过了,没有找到类似的结果,所以如果有人问我,我道歉。

无论如何,我正在生成一个多数组它是由一个漂亮的小类生成的。

无论如何,当输出

时,数组是这样的:
array(2047) {
    [0]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "26"
    }
    [1]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "42"
    }
    [2]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "16"
    }
    // and so on
}
我的问题是……是否有一个简单的php函数或一个整洁的方式排序数组到高到低使用点的值?

我已经看了一些php函数,但他们只是一个单一值的标准数组。

谢谢你的帮助:)

我试过了,它不按点排序。

这是我正在做的类:

//create sort value
private function sorting_table($a, $b){
    return $a['points'] - $b['points'];
}
//sort all users into a table and order the highest to the lowest
public function output_prediction_table($pdo, $year){
    //get all uers and put in an array with games played and points.
    $getallusers = $pdo->prepare("SELECT userid FROM userpredictions WHERE year=:year");
    $getallusers->execute(array(':year' => $year));
    //create the multidimentional array
    $multidimentional_array = array();
    while($fetchallusers = $getallusers->fetch()){
        $multidimentional_array[] = array(
            'name' => $this->get_username($pdo, $fetchallusers['userid']),
            'games' => $this->get_games_played($pdo, $year),
            'points' => $this->make_points($pdo, $year, $fetchallusers['userid']),
            'userid' => $fetchallusers['userid']
        );
    }
    usort($multidimentional_array, array($this, 'sorting_table'));
    $output = '<table class="table-striped">';
    $output .= '<tr class="t-h"><td class="t-c">Position</td><td>Username</td><td>Games Played</td><td>Points</td></tr>';
    $tablenumber = 1;
    foreach($multidimentional_array as $newarray){
        $output .= '<tr><td class="t-c">'.$tablenumber.'</td><td><a href="/user/'.$this->sluggify($newarray["name"]).'/'.$newarray["userid"].'/" title="View '.ucwords($newarray["name"]).' Profile">'.ucwords($newarray["name"]).'</a></td><td>'.$newarray["games"].'</td><td>'.$newarray["points"].'</td></tr>';
        $tablenumber++;
    }
    $output .= '</table>';
    return $output;
}

我没有得到任何错误,它只是没有排序从最高点先到最低点最后

尝试usort

你可以这样做:

usort($array, 'sortByPoints');
function sortByOrder($a, $b) {
    return $a['points'] - $b['points'];
}

你可以在这里找到更多的例子:排序多维数组的值

使用usort以下是完整的测试代码:

function sortByOrder($a, $b) {
    return $a['points'] - $b['points'];
}
$test = array(
    0=> array(
        "name"=> "name",
        "gamesplayed" => "26",
        "points" => "26"
    ),
    1=> array(
        "name"=> "name",
        "gamesplayed" => "26",
        "points" => "42",
    ),
    2=> array(
        "name"=> "name",
        "gamesplayed" => "26",
        "points" => "16",
    )
);
usort($test, 'sortByOrder');
print_r($test);

相关内容

  • 没有找到相关文章

最新更新