# Sorting multidimensional array by two criteria

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

•  Subject
• Author
• Posted on

I am trying to sort a multidimensional array by two criteria e.g.

\$output = array(1234, 3),
array(5678, 3),
array(1234, 2)

to produce

1234, 2
1234, 3
5678, 3

I see that the following code from the manual allows me to sort by one
criteria but how do I use two?

function cmp(\$a, \$b)
{
return strcmp(\$a[1], \$b[1]);
}

usort(\$output, "cmp");

Thanks,

Chris

## Re: Sorting multidimensional array by two criteria

Okay, a little light when on and I made life easier for myself
regarding previous post.

I was exploding a string such as '19 Nov 2009, 18:00', adding as part
of a multidimensional array, and then wanting to sort by day, hour.

The simple solution was to use strtotime and substr and concatenate
\$str[0] 1258588800 and \$str[1] 18 to get 125858880018 and sorting by
date, hour is easy.

Chris

## Re: Sorting multidimensional array by two criteria

.oO(Chris)

JFTR: Just in case you need multi-column sorting somewhere else, have a
look at array_multisort(). It's a really powerful function, even though
its usage can be a bit complicated.

Micha

## Re: Sorting multidimensional array by two criteria

function cmp(\$a, \$b, \$offset=3D0)
{
if (\$a[\$offset]=3D=3D\$b[\$offset]) {
if (array_key_exists(\$offset+1, \$a) || array_key_exists(\$offset
+1, \$b)) {
return cmp(\$a, \$b, \$offset+1);
} else return 0;
} else return \$a[\$offset] < \$b[\$offset] ? -1 : 1;
}

....or....
function cmp(\$a,\$b)
{
\$al=3Dimplode(' ',\$a);
\$bl=3Dimplode(' ',\$b);
return strcmp(\$al,\$bl);
}
...or....
(no, I got bored at this point - think up some more yourself)

C.