This question already has an answer here:
- How can I sort arrays and data in PHP? 9 answers
I have an array in this format:
Array
(
[0] => Array
(
[text] => tests
[language] =>
[advertiserCompetitionScale] => 5
[avgSearchVolume] => 7480000
[lastMonthSearchVolume] => 9140000
)
[1] => Array
(
[text] => personality tests
[language] =>
[advertiserCompetitionScale] => 5
[avgSearchVolume] => 165000
[lastMonthSearchVolume] => 201000
)
[2] => Array
(
[text] => online tests
[language] =>
[advertiserCompetitionScale] => 5
[avgSearchVolume] => 246000
[lastMonthSearchVolume] => 301000
)
)
How can I sort an array in that format, in the descending order of the avgSearchVolume
field? Is there a built in function for this?
This might help: Sorting Arrays of Arrays
Until PHP 5.3 this is the best function for sorting based on subkeys without making a new function for each key.
With PHP 5.3 you can make something like this, same function call as now.
Use
usort
and supply your own function to do the ordering, e.g.Here is another solution, You can add multiple options for sorting(See the commented section of the code)
REF: http://php.net/manual/en/function.array-multisort.php
You'll have to use a custom callback function together with
usort()
.