Page 1 of 1

Associative array sorting

Posted: Wed Sep 16, 2009 1:16 pm
by fredsnertz
I just can't figure out how to do complex sorting with PHP. Lets say I have this associative array:

$ips['10.2.3.4']['total']=6
$ips['10.3.4.5']['total']=22
$ips['10.99.53.5']['total']=3

All I want to do is sort numerically by "total". Assume I can not simplify the structure of the array. Each IP entry has fields other than "total" which I'm not showing for simplicity. Thanks.

Re: Associative array sorting

Posted: Wed Sep 16, 2009 1:46 pm
by pickle
array_multisort(), which is a real bugger to learn how to use.

Basically you iterate through your $ips array & move the value of the 'total' element into a new array - say $totals. This new array should still be keyed by ip. Then, run them both through array_multisort(). Look at example #3 on the array_multisort() page.

You'd be doing something like this (untested):

Code: Select all

array_multisort($totals, SORT_ASC, $ips);

Re: Associative array sorting

Posted: Wed Sep 16, 2009 1:53 pm
by fredsnertz
Worked great thanks!
It seems like the second array is a step that shouldn't be necessary but as you said its right there in the example.