根据特定列对数组进行排序

时间:2014-03-26 14:49:28

标签: php arrays sorting

我有一个输出如下所示数据的数组:

 [STU-CZC0226PVC] => Array
    (
        [ComputerName] => STU-CZC0226PVC
        [time_in_days] => 13
        [room] => 1N10
    )

[STU-FMDXZDHJF-M] => Array
    (
        [ComputerName] => STU-FMDXZDHJF-M
        [time_in_days] => 13
        [room] => 2R022
    )

[STU-CZC03184CM] => Array
    (
        [ComputerName] => STU-CZC03184CM
        [time_in_days] => 13
        [room] => 2Q11
    )

[STU-CZC0226PTM] => Array
    (
        [ComputerName] => STU-CZC0226PTM
        [time_in_days] => 13
        [room] => 1N10
    )

[STU-CZC12632SN] => Array
    (
        [ComputerName] => STU-CZC12632SN
        [time_in_days] => 13
        [room] => 1N75

我想对数组进行排序,以便将具有相同房间号的记录列在一起,但不知道如何做到这一点。我认为它可能会使用usort(),但我不知道如何实现它,并且想知道是否有人可以提供帮助?

由于

2 个答案:

答案 0 :(得分:0)

PHP> = 5.5.0

array_multisort(array_column($array, 'room', 'ComputerName'), SORT_DESC, $array);

PHP< 5.5.0

foreach($array as $key => $val) {
    $rooms[$key] = $val['room'];
}
array_multisort($rooms, SORT_DESC, $array);

答案 1 :(得分:0)

您可以将uasortstrcmp结合使用:

uasort($array, function ($a, $b) {
    return strcmp($a['room'], $b['room']);
});