Dcr163的博客 - usort
type: channel
link: http://dcr163.cn/tag/usort/
items: php使用usort排序多维数组内的值

php使用usort排序多维数组内的值
type: item
date: 2025-09-11T23:38:12+08:00
description: 直接上代码：$data = [ '一队' => [ 'counts' => 0, 'totals' => 0, 'team' => [ ['realname' => '张三', 'counts' => 10, 'totals' => 600], ['realname' => '张三2', 'counts' => 17, 'totals' => 478], ['realname' => '张三3', 'counts' => 190, 'totals' => 10000], ['realname' => '张三4', 'counts' => 8, 'totals' => 500], ] ], '二队' => [ 'counts' => 0, 'totals' => 0, 'team' => [ ['realname' => '李四', 'counts' => 10, 'totals' => 600], ['realname' => '李四2', 'counts' => 17, 'totals' => 478], ['realname' => '李四3', 'counts' => 190, 'totals' => 10000], ['realname' => '李四4', 'counts' => 8, 'totals' => 500], ] ], '三队' => [ 'counts' => 0, 'totals' => 0, 'team' => [ ['realname' => '王五', 'counts' => 10, 'totals' => 600], ['realname' => '王五2', 'counts' => 17, 'totals' => 478], ['realname' => '王五3', 'counts' => 190, 'totals' => 10000], ['realname' => '王五4', 'counts' => 8, 'totals' => 500], ['realname' => '王五5', 'counts' => 11, 'totals' => 600], ] ], ]; //数组根据指定key排序 foreach ($data as $key => &$val) { usort($val['team'], function ($a, $b) { //根据totals从高到低排序 if ($a['totals'] != $b['totals']) { if ($a['totals'] > $b['totals']) { // 如果是 < 就是从低到高排序 return -1; } elseif ($a['totals'] == $b['totals']) { return 0; } else { return 1; } //php7+可以这么写,使用航天飞船符 <=> 更简洁，逻辑清晰 //return $b['totals'] <=> $a['totals']; } //根据counts从高到底排序 if ($a['counts'] > $b['counts']) { // 如果是 < 就是从低到高排序 return -1; } elseif ($a['counts'] == $b['counts']) { return 0; } else { return 1; } //php7+可以这么写,使用航天飞船符 <=> 更简洁，逻辑清晰 //return $b['counts'] <=> $a['counts']; }); } unset($val); echo ' '; print_r($data); 看看最终输出的结果：Array ( [一队] => Array ( [counts] => 0 [totals] => 0 [team] => Array ( [0] => Array ( [realname] => 张三3 [counts] => 190 [totals] => 10000 ) [1] => Array ( [realname] => 张三 [counts] => 10 [totals] => 600 ) [2] => Array ( [realname] => 张三4 [counts] => 8 [totals] => 500 ) [3] => Array ( [realname] => 张三2 [counts] => 17 [totals] => 478 ) ) ) [二队] => Array ( [counts] => 0 [totals] => 0 [team] => Array ( [0] => Array ( [realname] => 李四3 [counts…