Another way would also be using the function uasort
, where you order the array
according to a past callback. We use count
us array
internally compared the callback
to determine which position will 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 order it like this:
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 so:
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,
),
)