Sorting an associative array in PHP [duplicate]

Use usort and supply your own function to do the ordering, e.g.

function cmp($a, $b)
{
    return $b['avgSearchVolume'] - $a['avgSearchVolume'];
}

usort($array, "cmp");

Until PHP 5.3 this is the best function for sorting based on subkeys without making a new function for each key.

function sortBySubkey(&$array, $subkey, $sortType = SORT_ASC) {
    foreach ($array as $subarray) {
        $keys[] = $subarray[$subkey];
    }
    array_multisort($keys, $sortType, $array);
}
sortBySubkey($arr, 'avgSearchVolume');

With PHP 5.3 you can make something like this, same function call as now.

function getSortVariable($sortType = SORT_ASC) {
    switch($sortType) {
        case SORT_ASC:
            return function ($a, $b) use ($subkey) { return strcmp($a[$subkey], $b[$subkey]); };
    }
}

function sortBySubkey(&$array, $subkey, $sortType = SORT_ASC) {
    $sortFunction = getSortVariable($sortType);
    usort($array, $sortFunction($subkey));
}