How would I sort this kind of array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

How would I sort this kind of array?

Post by kaisellgren »

Hi,

I have an array like

$array = array();

then looping something...
$array[] = array('content','score');
then end looping

now we have array consisting of multiple arrays. I want to sort my array based on the score.

Any ideas?
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

array_multisort()

How you'd sort this array is to iterate through it & pull out all the scores into a new array, with the new array having the same indices. Then you sort the score array, keeping index association. Use that newly sorted array with your original array in array_multisort() and it'll sort $array by score.

Specifically how you do that I'm not 100% sure. There is an example in the documentation that does pretty much exactly this.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Post by Zoxive »

Now it is possible to sort this the way you want, but why not tackle the source of this?

How are you looping? you may be able to sort it if you are looping this Data from a Database.

Ex.

Code: Select all

ORDER BY `Score` DESC
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

I have to back Zoxive's advice: do as much as you can at the SQL layer. It has much better performance than PHP.

If you have no choice, check out http://ca3.php.net/manual/en/function.usort.php
Post Reply