-4

my array is in this format

Array
(
    [0] => 1,3
    [1] => 2,0
    [2] => 5,2
    [3] => 28,1
    [4] => 30,2
    [5] => 33,0
    [6] => 36,0
    [7] => 38,0
    [8] => 39,0
    [9] => 40,0
    [10] => 42,2
    [11] => 45,6
    [12] => 56,1
    [13] => 58,1
    [14] => 68,0
    [15] => 70,0
    [16] => 71,0
    [17] => 75,0
    [18] => 76,0
    [19] => 77,0
    [20] => 78,0
    [21] => 83,1
    [22] => 86,0
    [23] => 87,2
    [24] => 88,0
    [25] => 89,0
    [26] => 91,0
)

and i want to sort the array in descending for example: the value in array [10] =>45,6 . want to sort according to second value i.e 6 in this array

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
Nav
  • 9
  • 1
  • 3
  • http://php.net/manual/en/function.usort.php – PeeHaa Oct 31 '13 at 11:25
  • 1
    This is where you write a custom function and use [u sort](http://php.net/manual/en/function.usort.php) which will let you do this. – Fluffeh Oct 31 '13 at 11:25
  • possible duplicate of [Reference: all basic ways to sort arrays and data in PHP](http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php) – Erbureth Oct 31 '13 at 11:28

2 Answers2

6

You can use a user defined function when sorting. This will do what you need it to do.

function cmp($a, $b)
{
    $aa = explode(',', $a)[1];
    $bb = explode(',', $b)[1];
    if ($aa == $bb) {
        return 0;
    }
    return ($aa > $bb) ? -1 : 1;
}

usort($array, 'cmp');
Pastor Bones
  • 7,183
  • 3
  • 36
  • 56
2

usort is your friend:

usort($array, function($a, $b){

  return explode(',', $b)[1] - explode(',', $a)[1];

});
moonwave99
  • 21,957
  • 3
  • 43
  • 64