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!

0

2 Answers 2

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

1
  • For brevity, you can do return $a['SORTNR'] - $b['SORTNR'] in your cmp() function Commented Nov 2, 2011 at 2: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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.