How to Sort an Associative Array by Key in PHP [Duplicate]
Sorting an array can be a common task in programming, especially when dealing with data structures like associative arrays in PHP. These arrays are similar to regular arrays, but allow you to access elements by keys instead of numerical indices.
Problem:
You have an associative array with elements like the one shown below:
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 ) )
You want to sort this array in descending order based on the "avgSearchVolume" field.
Solution:
PHP provides a built-in function called usort that you can use for this purpose. usort takes two arguments: an array to sort and a comparison function. The comparison function takes two array elements as arguments and returns a negative integer, zero, or a positive integer:
To sort your array, you can define a comparison function like this:
function cmp($a, $b) { return $b['avgSearchVolume'] - $a['avgSearchVolume']; }
This function subtracts the "avgSearchVolume" field of the first element from the "avgSearchVolume" field of the second element. If the result is negative, it means the second element should come before the first element. If it's zero, the elements are considered equal. If it's positive, the first element should come before the second.
Finally, you can call usort and pass your comparison function as the second argument:
usort($array, "cmp");
After calling usort, your array will be sorted in descending order by the "avgSearchVolume" field.
The above is the detailed content of How to Sort a Multidimensional Associative Array in PHP by a Specific Key?. For more information, please follow other related articles on the PHP Chinese website!