homepage Welcome to WebmasterWorld Guest from 54.205.254.108
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Sorting multi-dimensional arrays. Help!
zootreeves




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

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

 

zootreeves




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

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

jatar_k




msg:1272455
 8:56 pm on Oct 29, 2005 (gmt 0)

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.

coopster




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

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

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved