PHP:按子值排序数组

时间:2011-11-01 23:18:53

标签: php arrays sorting

  

可能重复:
  How to sort arrays inside an array?
  Sort an array by a child array's value in PHP

我有一个看起来像这样的数组:

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

现在我想使用[SORTNR]降序的值对子数组进行排序,所以在这里它最终应该是这样的:

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

如何在PHP中正确执行此操作?我现在尝试了一些东西四个小时,我找不到任何好的解决方案......

寻求帮助!

2 个答案:

答案 0 :(得分:2)

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

uasort($arr, 'cmp');

代码改编自PHP uasort() manual page

答案 1 :(得分:1)

如果要排序的子值是可变的,您还可以考虑使用array_multisort()。参见示例#3:http://php.net/array_multisort