PHP排序多维数组由项目数 [英] PHP Sort a multidimensional array by number of items
本文介绍了PHP排序多维数组由项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,如:
Array
(
[DEF] => Array
(
[0] => Array
(
[type] => 1
[id] => 1212
[name] => Jane Doe
[current] => 1
)
[1] => Array
(
[type] => 1
[id] => 3123121
[name] => Door
[current] =>
)
)
[ABC] => Array
(
[0] => Array
(
[type] => 1
[id] => 1234
[name] => John Doe
[current] =>
)
)
[WW] => Array
(
[0] => Array
(
[type] => 1
[id] => 1212
[name] => Jane Doe
[current] => 1
)
[1] => Array
(
[type] => 1
[id] => 3123121
[name] => Door
[current] =>
)
[2] => Array
(
[type] => 1
[id] => 64646
[name] => Floor
[current] =>
)
)
)
和我想排序这个数组由数内数组项(即第一大部分项目)的递减(COUNT()),这样我就有这个数组:
And I want to sort this array by number ( count() ) of inner-array items descending (i.e. most items first), so I will have this array:
Array
(
[WW] => Array
(
[0] => Array
(
[type] => 1
[id] => 1212
[name] => Jane Doe
[current] => 1
)
[1] => Array
(
[type] => 1
[id] => 3123121
[name] => Door
[current] =>
)
[2] => Array
(
[type] => 1
[id] => 64646
[name] => Floor
[current] =>
)
)
[DEF] => Array
(
[0] => Array
(
[type] => 1
[id] => 1212
[name] => Jane Doe
[current] => 1
)
[1] => Array
(
[type] => 1
[id] => 3123121
[name] => Door
[current] =>
)
)
[ABC] => Array
(
[0] => Array
(
[type] => 1
[id] => 1234
[name] => John Doe
[current] =>
)
)
)
任何人都可以提出一个有效的方式来做到这一点?谢谢你。
Can anyone suggest an efficient way to do so? Thanks.
推荐答案
使用 uksort
一>:
uksort($array, function($a, $b) { return count($b) - count($a); });
使用在array_multisort
:
array_multisort(array_map('count', $array), SORT_DESC, $array);
使用PHP< 5.3:
With PHP < 5.3:
function sort_cb($a, $b) {
return count($b) - count($a);
}
uksort($array, 'sort_cb');
这篇关于PHP排序多维数组由项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文