1

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
        )

)
Query Master
  • 6,989
  • 5
  • 35
  • 58

4 Answers4

4

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);
Josh
  • 8,082
  • 5
  • 43
  • 41
0
usort($list, function($entry1, $entry2) {return strcmp($entry1['avg_pred_error'], $entry2['avg_pred_error']);});

The result is then in $list

Broncko
  • 193
  • 1
  • 6
0

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

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
0

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 );
Berry Langerak
  • 18,561
  • 4
  • 45
  • 58