Jump to content

How to sort this multidimensional array by one of its key's?


the5thace

Recommended Posts

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. 

 

 

 

 

 

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.