-1

Possible Duplicate:
Sorting an associative array in PHP

I have an array that looks like the below one. I need to order it by the points values Highest to lowest. I have tried all the sorting functions and some bring back crazy results.

(
  [0] => Array
  (
    [name] => Shane Jones
    [points] => 43
  )
  [1] => Array
  (
    [name] => Katie 'Kitty' Youd
    [points] => 50
  )
  [2] => Array
  (
    [name] => Steve Bennett
    [points] => 50
  )
  [3] => Array
  (
    [name] => Sharon Harvey
    [points] => 99
  )
  [4] => Array
  (
    [name] => Sean Dentith
    [points] => 50
  )

)
Community
  • 1
  • 1
Shane Jones
  • 885
  • 1
  • 9
  • 27
  • 1
    Yeah, your problem arises as it's a multi-dimensional array, and the array sorting functions will only affect the outer-most array. How is this array created? Is it hard-coded or does it come from a data source, say a database or an XML file? – Martin Bean Oct 06 '11 at 11:50
  • 1
    A similar question has already been posed *and* answered: [Sorting an associative array in PHP](http://stackoverflow.com/questions/777597/sorting-an-associative-array-in-php). Please use the search function next time. See the [FAQ](http://stackoverflow.com/faq). – hakre Oct 06 '11 at 11:51

2 Answers2

2

See Example #3 in the PHP Manual entry for array_multisort

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
1

Use usort().

usort($data, function($a, $b) {
    return $a['points'] - $b['points'];
});
alex
  • 479,566
  • 201
  • 878
  • 984