在php中按两个值对多维数组进行排序

时间:2017-12-18 16:01:15

标签: php sorting multidimensional-array

我有一个如下所示的数组

Array
(
[0] => Array
    (
        [room] => kh-332
        [type] => Computer Lab
        [description] => K Lab
        [availability] => available

    )

[1] => Array
    (
        [room] => mh-112
        [type] => Conference Room
        [description] => Chute Room
        [availability] => conflict
        )

[2] => Array
    (
        [room] => mh-227
        [type] => Classroom
        [description] => EMCC Class
        [availability] => available
        )
[3] => Array
    (
        [room] => mh-500
        [type] => Lab
        [description] => Auto Lab
        [availability] => available
        )
[4] => Array
    (
        [room] => mh-125
        [type] => Classroom
        [description] => Accuplacer Testing
        [availability] => conflict
        )
[5] => Array
    (
        [room] => mh-225
        [type] => Computer Lab
        [description] => Kaplan Testing 
        [availability] => available
        )
[6] => Array
    (
        [room] => mh-111
        [type] => Conference Room
        [description] => Video Conference
        [availability] => conflict
        )
)

我需要先按类型对数组进行排序,然后按房间名称对数组进行排序,以便所有计算机实验室都按数组排序,按房间按字母顺序排序。我使用下面的函数按类型对数组进行排序,但是我遇到了一些困难,然后按房间按字母顺序对类型组进行排序。非常感谢任何帮助。

function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
    $sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
    $ret[$ii]=$array[$ii];
}
$array=$ret;
}

1 个答案:

答案 0 :(得分:-1)

我更多地挖掘了usort(),我找到了问题的答案,这很有效。

usort($merge,function($a,$b){
    $c = strcmp($a['type'],$b['type']);
    $c .= strcmp($a['availability'],$b['availability']);
    $c .= strcmp($a['room'],$b['room']);
    return $c;
});