Jump to content

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


the5thace
Go to solution Solved by requinix,

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. 

 

 

 

 

 

Link to comment
Share on other sites

  • Solution

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.