0

Possible Duplicate:
How to sort arrays inside an array?
Sort an array by a child array's value in PHP

I've got an array that looks like this:

[0] => Array {
    [ID] => 1651,
    [DESCR] => "blabla",
    [SORTNR] => 1,
},
[1] => Array {
    [ID] => 456,
    [DESCR] => "bleble",
    [SORTNR] => 3,
},
[2] => Array {
    [ID] => 158,
    [DESCR] => "bliblablub",
    [SORTNR] => 2,
},

Now I want to sort the subarrays using the value of [SORTNR] descending, so here it should finally look like that:

[1] => Array {
    [ID] => 456,
    [DESCR] => "bleble",
    [SORTNR] => 3,
},
[2] => Array {
    [ID] => 158,
    [DESCR] => "bliblablub",
    [SORTNR] => 2,
},
[0] => Array {
    [ID] => 1651,
    [DESCR] => "blabla",
    [SORTNR] => 1,
},

How can I do that correctly in PHP? I tried some stuff now for four hours and I couldn't find any good solution....

Thx for help!

Community
  • 1
  • 1
Florian Müller
  • 6,344
  • 25
  • 70
  • 114

2 Answers2

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

uasort($arr, 'cmp');

Code adapted from PHP uasort() manual page

Clive
  • 36,705
  • 8
  • 79
  • 108
  • For brevity, you can do `return $a['SORTNR'] - $b['SORTNR']` in your cmp() function – Vikk Nov 02 '11 at 02:34
1

If the subvalue you want to sort by is variable, you might also consider using array_multisort(). See Example #3: http://php.net/array_multisort

Matthew Turland
  • 753
  • 3
  • 11