Reputation: 55
Here I have a multidimentional array looks like this:
Array
(
[1] => Array
(
[0] => 100
[1] => a
)
[2] => Array
(
[0] => 1000
[1] => b
)
[3] => Array
(
[0] => 50
[1] => c
)
[4] => Array
(
[0] => 500
[1] => d
)
[5] => Array
(
[0] => 1500
[1] => e
)
)
All I wanna do is sorting the array based on the [0] value, so it will be look like this:
Array
(
[1] => Array
(
[0] => 1500
[1] => e
)
[2] => Array
(
[0] => 1000
[1] => b
)
[3] => Array
(
[0] => 500
[1] => d
)
[4] => Array
(
[0] => 100
[1] => a
)
[5] => Array
(
[0] => 50
[1] => c
)
)
Do you have any suggestion what I'm suppose to do? Thanks in advance
Upvotes: 0
Views: 51
Reputation: 42925
Easiest is to use a user defined function for sorting:
<?php
$values = [
1 => [100, 'a'],
2 => [1000, 'b'],
3 => [50, 'c'],
4 => [500, 'd'],
5 => [1500, 'e']
];
usort($values, function($a, $b){
return $a[0] < $b[0];
});
var_dump($values);
The output obviously is:
array(5) {
[0] =>
array(2) {
[0] =>
int(1500)
[1] =>
string(1) "e"
}
[1] =>
array(2) {
[0] =>
int(1000)
[1] =>
string(1) "b"
}
[2] =>
array(2) {
[0] =>
int(500)
[1] =>
string(1) "d"
}
[3] =>
array(2) {
[0] =>
int(100)
[1] =>
string(1) "a"
}
[4] =>
array(2) {
[0] =>
int(50)
[1] =>
string(1) "c"
}
}
Upvotes: 1