Sort a multidimensional array with numeric values
Suppose the following situation in which I have a array
consisting of several array
with numeric values:
$array = array(
array(22, 25, 28),
array(22),
array(22, 23)
)
I would like to leave this array
sorted as follows:
$array = array(
array(22),
array(22, 23),
array(22, 25, 28)
)
What would be the algorithm for this case?
3 answers
Use the function asort():
This function sorts an array so that the correlation between indexes and values is maintained. It is mainly used to sort associative arrays where the order of elements is an important factor.
Example:
$array = array(
array(22, 25, 28),
array(22),
array(22, 23)
);
asort($array);
Result:
var_dump($array);
array(3) {
[1]=>
array(1) {
[0]=>
int(22)
}
[2]=>
array(2) {
[0]=>
int(22)
[1]=>
int(23)
}
[0]=>
array(3) {
[0]=>
int(22)
[1]=>
int(25)
[2]=>
int(28)
}
}
Try This:
array_multisort($array);
print_r($array);
Anything looking for something around here: link
Another way would also be by using the function uasort
, where you sort the array
according to a passed callback. We use count
in the internally compared array
of 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 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 like this:
uasort($a, function ($a, $b) {
return count($b) - count($a);
})
print_r($a);
The result series:
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,
),
)