网站首页 » PHP » array_multisort 使用示例

array_multisort 使用示例

June 18, 2022 PHP

多维数组按字段多次排序

$arr = array();
for ($i = 1;$i<10;$i++){
    $item = array();
    $item['name'] = 'name-' . $i;
    $item['number'] = rand(10,99);
    $item['sort'] = rand(1,10);
    $arr[] = $item;
}
var_dump(json_encode($arr));
// string(352) "[{"name":"name-1","number":53,"sort":1},{"name":"name-2","number":56,"sort":6},{"name":"name-3","number":39,"sort":6},{"name":"name-4","number":46,"sort":3},{"name":"name-5","number":33,"sort":8},{"name":"name-6","number":64,"sort":6},{"name":"name-7","number":48,"sort":4},{"name":"name-8","number":50,"sort":5},{"name":"name-9","number":12,"sort":2}]"

/**
 * 提取要排序的字段
 */
$number_index = array_column($arr,'number');
$sort_index = array_column($arr,'sort');
/**
 * 按指定规则多次排序
 */
//只排序一次
//array_multisort($number_index,SORT_ASC,$arr);
//多字段排序
array_multisort($number_index,SORT_ASC,$sort_index,SORT_DESC,$arr);

var_dump(json_encode($arr));
//string(352) "[{"name":"name-9","number":12,"sort":2},{"name":"name-5","number":33,"sort":8},{"name":"name-3","number":39,"sort":6},{"name":"name-4","number":46,"sort":3},{"name":"name-7","number":48,"sort":4},{"name":"name-8","number":50,"sort":5},{"name":"name-1","number":53,"sort":1},{"name":"name-2","number":56,"sort":6},{"name":"name-6","number":64,"sort":6}]"