Home >Backend Development >PHP Tutorial >How to Sort a PHP Associative Array by Average Search Volume?
Sorting an Associative Array by Average Search Volume in PHP
Sorting an associative array by a specific field, such as avgSearchVolume, requires a custom sorting function. PHP provides the usort() function to perform user-defined sorting on arrays.
Sorting Function:
To sort the given array in descending order of the avgSearchVolume field, define a comparison function as follows:
function cmp($a, $b) { return $b['avgSearchVolume'] - $a['avgSearchVolume']; }
This function subtracts the avgSearchVolume value of $a from that of $b, resulting in a positive value if $b's value is greater. This ensures that higher avgSearchVolume values will be placed earlier in the sorted array.
Sorting the Array:
Once the comparison function is defined, pass the associative array and the function name to the usort() function:
usort($array, "cmp");
After this line of code, the $array will be sorted in descending order of the avgSearchVolume field.
The above is the detailed content of How to Sort a PHP Associative Array by Average Search Volume?. For more information, please follow other related articles on the PHP Chinese website!