Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an associative array in PHP [duplicate]

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?

like image 745
Ali Avatar asked Apr 22 '09 14:04

Ali


People also ask

How do you sort an associative array in PHP?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

How are duplicates removed from a given array in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.


2 Answers

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"); 
like image 166
Paul Dixon Avatar answered Sep 23 '22 15:09

Paul Dixon


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)); } 
like image 34
OIS Avatar answered Sep 20 '22 15:09

OIS