1

嘿,Guyz,我在数组排序方面遇到问题,如果您对此有任何解决方案,我不知道如何解决这个问题,然后回答我

基本上我想像这样avg_pred_error(从低到高)对这个数组进行排序36 39 39 41

Array
(
    [0] => Array
        (
            [avg_pred_error] => 39
            [user_name] => Abdul Samad
        )

    [1] => Array
        (
            [avg_pred_error] => 41
            [user_name] => Kane Marcus
        )

    [2] => Array
        (
            [avg_pred_error] => 39
            [user_name] => Sam Shawn
        )

    [3] => Array
        (
            [avg_pred_error] => 36
            [user_name] => Axel Woodgate
        )

)
4

4 回答 4

4

使用usort. 以下基本上是手册中的基本示例:

function cmp($a, $b) {
    if ($a['avg_pred_error'] == $b['avg_pred_error'])
        return 0;

    return ($a['avg_pred_error'] < $b['avg_pred_error']) ? -1 : 1;
}

// Sort (LOW to HIGH) and print the resulting array
usort($array, 'cmp');
print_r($array);
于 2012-04-10T14:51:47.880 回答
0
usort($list, function($entry1, $entry2) {return strcmp($entry1['avg_pred_error'], $entry2['avg_pred_error']);});

然后结果在 $list

于 2012-04-10T14:52:21.977 回答
0

采用usort

function sortAvg($a, $b) {
        return $a['avg_pred_error'] - $b['avg_pred_error'];
}

usort($input, 'sortAvg');
print_r($input);

http://sg.php.net/manual/en/function.usort.php

于 2012-04-10T14:52:48.653 回答
0

幸运的是,这相当简单。使用uasort提供您自己的比较函数:

<?php
$foo = array(
    array(
        'avg_pred_error' => 39,
        'user_name' => 'Abdul Samad'
    ),
    array(
        'avg_pred_error' => 41,
        'user_name' => 'Kane Marcus'
    ),
    array(
        'avg_pred_error' => 39,
        'user_name' => 'Sam Shawn'
    ),
    array(
        'avg_pred_error' => 36,
        'user_name' => 'Axel Woodgate'
    )
);

$sort = function( $a, $b ) {
    if( $a['avg_pred_error'] === $b['avg_pred_error'] ) {
        return 0;
    }
    return $a['avg_pred_error'] < $b['avg_pred_error'] ? '-1' : '1';
};

uasort( $foo, $sort );

var_dump( $foo );
于 2012-04-10T14:58:51.397 回答