PHP:$ array [$ i] ['v']; $ array [$ i] ['c']类型的多维数组排序,同时保留顺序

时间:2012-07-21 14:01:04

标签: php arrays multidimensional-array sorting

  

可能重复:
  PHP: sorting a multidimentional array ($arr[$i]['v'])

我有一个UNSORTED VERSION类型的数组。

$arr['foo']['man']      = 5;
$arr['foo']['str']      = 'string5';
$arr['foobar']['man']   = 2;
$arr['foobar']['str']   = 'string2';
$arr['barfoo']['man']   = 4;
$arr['barfoo']['str']   = 'string4';
$arr['foofoo']['man']   = 1;
$arr['foofoo']['str']   = 'string1';
$arr['bar']['man']      = 3;
$arr['bar']['str']      = 'string3';

我想按顺序对它进行排序,同时保留该数组中的所有其他数据,即

$arr['foo']['man']      = 5;
$arr['foo']['str']      = 'string5';
$arr['barfoo']['man']   = 4;
$arr['barfoo']['str']   = 'string4';
$arr['bar']['man']      = 3;
$arr['bar']['str']      = 'string3';
$arr['foobar']['man']   = 2;
$arr['foobar']['str']   = 'string2';
$arr['foofoo']['man']   = 1;
$arr['foofoo']['str']   = 'string1';

我已经在PHP中查看了许多排序函数,但还没有找到任何解决方案。

任何人都可以帮助我吗?提前谢谢。

2 个答案:

答案 0 :(得分:2)

使用uasort并传递自定义比较callable:

function compareItems($a, $b) {
    return $b['man'] - $a['man'];
}

uasort($arr, 'compareItems');

答案 1 :(得分:1)

uasort($arr, function($l, $r){
    return $r['man'] - $l['man'];
})