Grouping an Array

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
robbrown
Forum Newbie
Posts: 2
Joined: Wed Oct 20, 2004 12:56 pm

Grouping an Array

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

[php_man]usort()[/php_man]
robbrown
Forum Newbie
Posts: 2
Joined: Wed Oct 20, 2004 12:56 pm

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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;
}
Post Reply