Another way would also be to use the uasort
function, where you sort array
according to a last callback. We use count
in array
internally compared callback
to determine which position is to be ordered.
Let's imagine the following array
:
$a = array (
0 =>
array (
0 => 1,
1 => 2,
),
1 =>
array (
0 => 1,
),
2 =>
array (
0 => 1,
1 => 3,
2 => 4,
3 => 5,
),
3 =>
array (
0 => 1,
1 => 3,
),
);
We could sort it as follows:
uasort($a, function ($a, $b) {
return count($a) - count($b);
})
The result would be:
array (
1 =>
array (
0 => 1,
),
0 =>
array (
0 => 1,
1 => 2,
),
3 =>
array (
0 => 1,
1 => 3,
),
2 =>
array (
0 => 1,
1 => 3,
2 => 4,
3 => 5,
),
)
If you wanted this result in reverse order, you could do this:
uasort($a, function ($a, $b) {
return count($b) - count($a);
})
print_r($a);
The result would be:
array (
2 =>
array (
0 => 1,
1 => 3,
2 => 4,
3 => 5,
),
3 =>
array (
0 => 1,
1 => 3,
),
0 =>
array (
0 => 1,
1 => 2,
),
1 =>
array (
0 => 1,
),
)