# multi sorting multi dimensional array?

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

Hey all,

I have been using usort to sort my multi dimensional arrays ...

function cmp(\$a, \$b){
if(\$a[0] == \$b[0]){
return 0;
}
return (\$a[0] < \$b[0]) ? -1 : 1;
}
usort(\$searchResults, 'cmp');

Which works fine, but I need to sort by one element in the array, then
another, preserving the previous sort.

lets say the array is as follows:

array[0] = array[0] = foo
[1] = 2
[1] = array[0] = foo
[1] = 0
[2] = array[0] = bar
[1] = 1
[3] = array[0] = bar
[1] = 0
[4] = array[0] = foo
[1] = 1
[5] = array[0] = bar
[1] = 2

Initially, I sort the array in to groups based on array[?][0] using
usort as above so the output is :

foo, 2
foo, 0
foo, 1
bar, 1
bar, 2
bar, 0

Next though, I would like to sort this output by number (array[?][1])
in the groups so that the output is :

foo, 0
foo, 1
foo, 2
bar, 0
bar, 1
bar, 2

Is this possible? I am completely at a loss as to how to do this ...

Please help! :)

Cheers,

Eclectic

## Re: multi sorting multi dimensional array?

Yes, and it's quite simple, int the cmp you should first check on index
0 is (eg -strcmp), if the result equals 0 that means this and next
element have the same index 0 (eg foo), thus instead of sorting on 0 for
these 2 elements you should use index 1.

The actual cmp function is left to the execise of the reader :)

## Re: multi sorting multi dimensional array?

I understand that, but what I want do is sort the aray by index 0 so
that all the 'foo' and 'bar' are grouped, then keeping these grouped,
sort by index 1 (number) so that the results are grouped by index 0,
and each group is in order of number (index 1) ... make sence?

## Re: multi sorting multi dimensional array?

On 16 Mar 2005 23:06:48 -0800, Eclectic wrote:

That's exactly what he said. See http://php.net/usort
In the compare function "cmp(\$a,\$b)", first check the order of \$a[0] and
\$b[0], if not equal return -1 or 1 from function, if equal return the
order of \$a[1] and \$b[1].

--
Firefox Web Browser - Rediscover the web - http://getffox.com /
Thunderbird E-mail and Newsgroups - http://gettbird.com /

## Re: multi sorting multi dimensional array?

That is what I (tried) to explain:

function comparator
{
compare index 0

if equal
compare index 1

return result
}

The actual code is trivial and left for your excersize.

## Re: multi sorting multi dimensional array?

*click* ... cheers ... got it :)