PHP如何对一个数组进行多字段排序

多字段排序使用array_multisort()函数。

array_multisort()函数能够实现对多字段进行排序,相似对表数据进行排序操做。
例如:php

地区 热度 数量
北京 32 1
上海 36 18
广州 4 9
深圳 43 6
杭州 99 77
成都 99 80
昆明 4 6
重庆 99 60

代码以下:函数

<?php
$arr = [
    ['num' => '1','heat' => 32,'name' => '北京'],
    ['num' => '18','heat' => 36,'name' => '上海'],
    ['num' => '9','heat' => 4,'name' => '广州'],
    ['num' => '19','heat' => 36,'name' => '意义'],
    ['num' => '6','heat' => 43, 'name' => '深圳'],
    ['num' => '77','heat' => 99,'name' => '杭州'],
    ['num' => '78','heat' => 99,'name' => '成都'],
    ['num' => '6','heat' => 4,'name' => '昆明'],
    ['num' => '60','heat' => 99,'name' => '重庆'],
];

foreach ($arr as $key => $row) {
    $heat[$key] = $row['heat'];
    $num[$key] = $row['num'];
}
//将把 heat 降序排列,把 num 升序排列, 把 $arr 做为最后一个参数,以通用键排序
array_multisort($heat, SORT_DESC, $num, SORT_ASC, $arr);
print_r($arr);