有人能帮助我吗?我正在尝试按内部数组的长度(降序)对二维数组进行排序。
这个数组:
Array
(
[0] => Array
(
[0] => "a"
)
[1] => Array
(
[0] => "a"
[1] => "b"
[2] => "c"
)
[2] => Array
(
[0] => "a"
[1] => "b"
)
)
应该产生这个排序的数组:
Array
(
[0] => Array
(
[0] => "a"
[1] => "b"
[2] => "c"
)
[1] => Array
(
[0] => "a"
[1] => "b"
)
[2] => Array
(
[0] => "a"
)
)
你有提示吗?
答案 0 :(得分:1)
// Comparison function
function cmp($a, $b) {
$ca = count($a);
$cb = count($b);
if($ca == $cb)
return 0;
return ($ca < $cb ) ? -1 : 1;
}
// Sort the array
uasort($array, 'cmp');
答案 1 :(得分:0)
是的,使用usort
按count()
元素排序。
<?php
header("Content-type: text/plain");
$array = array(
array(
"item1" => "key1",
"item2" => "key2",
),
array(
"item1" => "key1",
"item2" => "key2",
"item3" => "key3"
),
array(
"item1" => "key1",
)
);
usort($array, function($el1, $el2) {
if (count($el1) === count($el2)) {
return 0;
}
return count($el1) < count($el2) ? 1 : -1;
});
print_r($array);