Page 1 of 1

How would I sort this kind of array?

Posted: Wed Oct 17, 2007 11:37 am
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?

Posted: Wed Oct 17, 2007 11:53 am
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.

Posted: Wed Oct 17, 2007 11:54 am
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

Posted: Wed Oct 17, 2007 3:00 pm
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