Welcome to WebmasterWorld Guest from 54.205.130.92

Forum Moderators: coopster & jatar k

Sorting multi-dimensional arrays. Help!

   
8:10 pm on Oct 29, 2005 (gmt 0)

10+ Year Member



Hi,

I am writing a meta search engine script and each results gets a score based on a number of factors. What I'm trying to do is sort the results with the highest score first, ready for output.

So the Array looks like this

array(2) {
[0]=> array(4) {
[Title]=> "My site"
[Description]=> "whatever"
[Url]=> "url.com"
[Score]=> "200"
}
[1]=> array(4) {
[Title]=> "My site2"
[Description]=> "whatever"
[Url]=> "url.com"
[Score]=> "223"
}
}

Obviuosly there are more than 2 results in real life, but is there anyway to sort the array so My Site2, with a score of 223 will appear first? Thanks For Reading

8:52 pm on Oct 29, 2005 (gmt 0)

10+ Year Member



Usually when I've got a problem with php I can find a way around it, but this has completely got me stumped. the only way I can think Of doing It is to put in a mysql database and then query with the ORDER_BY option. Any help would be greatly appreciated
8:56 pm on Oct 29, 2005 (gmt 0)

WebmasterWorld Administrator jatar_k is a WebmasterWorld Top Contributor of All Time 10+ Year Member



I have used array_multisort [php.net] in the past.

I remember it being a bit tricky but it looks like there is a much better description there now.

5:10 pm on Oct 31, 2005 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



I have used it too, but array_multisort() requires an array of columns so we have to create code to obtain the columns in their own array first then perform the sorting. There is an example on the page referred to by jk that demonstrates how to do so. I prefer sorting the array with PHP's user-defined functions. I have hard-coded the sort index in the sorting function:
function cmp($a, $b) { 
return ($a['Score'] == $b['Score']) ? 0 : (($a['Score'] > $b['Score']) ? -1 : 1);
}
uasort [php.net]($array, 'cmp');
 

Featured Threads

Hot Threads This Week

Hot Threads This Month