Query Master
Query Master

Reputation: 7097

Array sorting issue (low to high)

Hey Guyz i have a issue in array sorting and i don't know how to slove this if you have any solution regarding this then answer me

basically i want sort this array with avg_pred_error (low to high) like this 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
        )

)

Upvotes: 1

Views: 554

Answers (4)

Berry Langerak
Berry Langerak

Reputation: 18859

Luckily, this is rather simple. Use uasort to supply your own comparison function:

<?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 );

Upvotes: 0

Andreas Wong
Andreas Wong

Reputation: 60526

Use 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

Upvotes: 0

Broncko
Broncko

Reputation: 193

usort($list, function($entry1, $entry2) {return strcmp($entry1['avg_pred_error'], $entry2['avg_pred_error']);});

The result is then in $list

Upvotes: 0

Josh
Josh

Reputation: 8191

Use usort. The following is essentially the basic example from the manual:

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);

Upvotes: 4

Related Questions