Page 1 of 1

Grouping an Array

Posted: Wed Oct 20, 2004 1:01 pm
by robbrown
I have an array

Code: Select all

ї0] => 1
ї1] => B
ї2] => NameOne

ї0] => 2
ї1] => C
ї2] => NameTwo

ї0] => 2
ї1] => A
ї2] => NameThree

ї0] => 2
ї1] => B
ї2] => NameFour
I would like to group all of the letters together (element 1 in each array) and then sort them so that the output will be:

Code: Select all

ї0] => 2
ї1] => A
ї2] => NameThree

ї0] => 1
ї1] => B
ї2] => NameOne

ї0] => 2
ї1] => B
ї2] => NameFour

ї0] => 2
ї1] => C
ї2] => NameTwo
Anyone have an idea on the best way to do this group and sort kind of array manipulation?

Posted: Wed Oct 20, 2004 1:24 pm
by feyd
[php_man]usort()[/php_man]

Posted: Wed Oct 20, 2004 2:29 pm
by robbrown
That's what I was thinking too. But it just seems to be sorting the array.

Here's the code I'm using. There must be a problem with it, but I'm having trouble finding it. Any ideas?

Code: Select all

function cmp_groups($a, $b) {
  if ($a < $b) return -1;
  if ($a > $b) return 1;

  return 0;
}

usort($output, "cmp_groups");

echo "<pre>";
print_r ($output);
echo "</pre>";
Thanks for your help, it is greatly appreciated.

Posted: Wed Oct 20, 2004 2:32 pm
by feyd

Code: Select all

function cmp_groups($a, $b)
{
  if($a&#1111;1] &gt; $b&#1111;1]) return -1;
  if($a&#1111;1] &lt; $b&#1111;1]) return 1;
  if($a&#1111;0] &gt; $b&#1111;0]) return -1;
  if($a&#1111;0] &lt; $b&#1111;0]) return 1;
  if($a&#1111;2] &gt; $b&#1111;2]) return -1;
  if($a&#1111;2] &lt; $b&#1111;2]) return 1;
  return 0;
}