the5thace Posted July 27, 2013 Share Posted July 27, 2013 I'm looking to sort this multidimensional array according to its integer value under the key name 'rank'. In other words $r_set contains the combined results of a number of search engines and each result is assigned a 'rank' according to which I want the array to be sorted. $r_set contents look like this -> $google[$google_count] = array ('url'=>$item->link, 'url_title'=>$item->title, 'snippet' =>$item->htmlSnippet, 'rank' => 100-$google_count, 'engine' => 'Google'); $google_count++; I load a number of these kinds of results(.ie $google[google_count] and others like it) in to $r_set when they have the same structure. I want $r_set to be sorted by its 'rank' key starting highest to lowest. Quote Link to comment https://forums.phpfreaks.com/topic/280580-how-to-sort-this-multidimensional-array-by-one-of-its-keys/ Share on other sites More sharing options...
Solution requinix Posted July 27, 2013 Solution Share Posted July 27, 2013 Either usort and you write a function that can compare two of those arrays to determine which comes first, function goggles($a, $b) { if ($a["rank"] != $b["rank"]) { return $a["rank"] - $b["rank"]; } else { // same rank so use something else to break the tie } } usort($google, "goggles");or array_multisort and you create a separate 1D array containing just the values you want to sort by. // as if $goggles = array($google[0]["rank"], $google[1]["rank"], $google[2]["rank"], ...) array_multisort($google, $goggles); Quote Link to comment https://forums.phpfreaks.com/topic/280580-how-to-sort-this-multidimensional-array-by-one-of-its-keys/#findComment-1442456 Share on other sites More sharing options...
Barand Posted July 28, 2013 Share Posted July 28, 2013 For a descending sort you need to return $b['rank'] - $a['rank'] Quote Link to comment https://forums.phpfreaks.com/topic/280580-how-to-sort-this-multidimensional-array-by-one-of-its-keys/#findComment-1442488 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.