Sorting arrays by an arbitary key value in PHP


I often (a couple times a month) have to sort an array of arrays by some arbitrary value located in the internal array. For example, I might want to sort the following structure by name.

   Array[0] {
      Array[0] {
         id => 1
         name => mike
         age => 20
      }

      Array[1] {
         id => 2
         name => bob
         age: 21
      }
   }

I want the same structure returned, but the array containing ‘bob’ in it’s name key must appear first in the array. PHP’s sort() function is insuffficient in this case, it sorts by the first key of each internal array (i.e. ‘id’ in this case).

The solution is to use usort(), which allows for a custom compare function to be used.

   function cmp($x, $y) {
      if ($x[1] == $y[1]) {
         return 0;
      } //if

      return ($x[1] > $y[1]) ? 1 : -1;
      //or return strcmp($x[1], $y[1]);
   } //cmp

   usort($array, 'cmp');

usort() takes the provided function name and uses it as the compare function between two elements. This also allows you to sort by multiple fields, if the first two fields are equal you can drop down to checking another field, and so on.

Share this post
  • Digg
  • StumbleUpon
  • Reddit
  • del.icio.us
  • Facebook
  • muti
  • Mixx
  • Google
  • laaik.it

This entry was posted on Tuesday, February 27th, 2007 at 1:22 pm and is filed under Code, MySQL. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Sorting arrays by an arbitary key value in PHP”

  1. Upendraya said this on

    This may not be revelant but i figured i’d post this anyway. If you’re using ubuntu 8.10 you may be in for some issues with the network manager. For some unknown reason it stops functioning. You will need to manually set you’re resolv.conf with your ISP’s DNS servers. That file is located in /etc/network/resolv.conf

Leave a Reply