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. 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...
requinix Posted July 27, 2013 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); 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'] 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
Archived
This topic is now archived and is closed to further replies.