I need to sort an array in PHP and then sort by its second index if the first index is the same. Let me explain :
The elements would be randomly arranged :
(2,1),(4,4),(2,9),(4,8),(2,35),(2,1),(2,35),(4,4),(4,25),(4,4)
I would need to sort them by the first number first. so the result would be :
(2,1),(2,9),(2,1),(2,35),(4,4),(4,8),(4,4),(4,25),(4,4)
Now you can see all the elements are grouped by the first index together. Now i need to group by the second index “WITHIN” the current grouping. Thus make it look like :
(2,1),(2,1),(2,9),(2,35),(4,4),(4,4),(4,4),(4,8),(4,25)
This was just a simple representation of the array. The actual array is below :
Array
(
[0] => Array
(
[practice_id] => 119
[practice_location_id] => 173
)
[1] => Array
(
[practice_id] => 2
[practice_location_id] => 75
)
[2] => Array
(
[practice_id] => 18
[practice_location_id] => 28
)
[3] => Array
(
[practice_id] => 119
[practice_location_id] => 174
)
[4] => Array
(
[practice_id] => 119
[practice_location_id] => 173
)
[5] => Array
(
[practice_id] => 2
[practice_location_id] => 75
)
[6] => Array
(
[practice_id] => 119
[practice_location_id] => 174
)
[7] => Array
(
[practice_id] => 18
[practice_location_id] => 28
)
[8] => Array
(
[practice_id] => 18
[practice_location_id] => 27
)
)
Would really appreciate some help.
This callback uses what I just learned from @casablanca’s answer, and puts it in a loop. This way, it won’t just compare two, but as many keys there are to compare.
As already stated, give this function as a callback to usort().
http://php.net/usort