Associative array sorting

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
fredsnertz
Forum Newbie
Posts: 4
Joined: Fri Aug 28, 2009 12:20 pm

Associative array sorting

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Associative array sorting

Post 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);
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

Post 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.
Post Reply