everisk Posted February 27, 2008 Share Posted February 27, 2008 I have an array that looks like below. I'd like to sort it in by [ctor] in descending order. Help please~. Thanks. Array ( [1] => Array ( [url] => www.abc.com [stimes] => 154 [ctor] => 19.06 ) [2] => Array ( [url] => www.123.com [stimes] => 90 [ctor] => 11.14 ) [3] => Array ( [url] => www.xyz.com [stimes] => 180 [ctor] => 22.28 ) ) Quote Link to comment Share on other sites More sharing options...
teng84 Posted February 27, 2008 Share Posted February 27, 2008 there is no predefined function for this you have use recursive function to sort this king of array! Quote Link to comment Share on other sites More sharing options...
Jessica Posted February 27, 2008 Share Posted February 27, 2008 http://php.net/usort Quote Link to comment Share on other sites More sharing options...
everisk Posted February 27, 2008 Author Share Posted February 27, 2008 Thank you for all your responses. The thing is i'm quite an amateur in PHP so I dont know how to write my own function to sort the array :'( . If anyone can help, I'd greatly appreciate it. Quote Link to comment Share on other sites More sharing options...
Barand Posted February 27, 2008 Share Posted February 27, 2008 <?php function mysort($a, $b) { return $a['ctor'] - $b['ctor']; } usort ($myarray, 'mysort'); Quote Link to comment Share on other sites More sharing options...
everisk Posted March 3, 2008 Author Share Posted March 3, 2008 thank you. but that doesn't seem to work Quote Link to comment Share on other sites More sharing options...
Barand Posted March 3, 2008 Share Posted March 3, 2008 it gave me Array ( [0] => Array ( [url] => www.123.com [stimes] => 90 [ctor] => 11.14 ) [1] => Array ( [url] => www.abc.com [stimes] => 154 [ctor] => 19.06 ) [2] => Array ( [url] => www.xyz.com [stimes] => 180 [ctor] => 22.28 ) ) which looks sorted to me. Define "doesn't work" Quote Link to comment Share on other sites More sharing options...
Barand Posted March 3, 2008 Share Posted March 3, 2008 Just re-read first post. To get DESC sort you need to reverse the sign of the value returned by the function function mysort($a, $b) { return $b['ctor'] - $a['ctor']; // B-A for descending } usort ($myarray, 'mysort'); // use uasort() if you want to preserve array indexes Quote Link to comment Share on other sites More sharing options...
everisk Posted March 4, 2008 Author Share Posted March 4, 2008 Oh right. Sorry.. I made some mistakes. Look like it's working now. Thanks a lot, Barand! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.