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.
Associative array sorting
Moderator: General Moderators
Re: Associative array sorting
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):
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);Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
-
fredsnertz
- Forum Newbie
- Posts: 4
- Joined: Fri Aug 28, 2009 12:20 pm
Re: Associative array sorting
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.
It seems like the second array is a step that shouldn't be necessary but as you said its right there in the example.