#native_company# #native_desc#
#native_cta#

Sorting a hierarchial listing for pulldowns.

By Philip Halsltrom
on November 2, 2000

Let’s say you want to sort a heirarchial list of categories to display in a pulldown menu. You could do something like the following:

Table Definition:


  id          INT
  parent_id   INT
  name        INT

$result = somedb_query("SELECT id, parent_id, name FROM mytable ORDER BY name");

while( $row = somedb_fetch_object($result) )  {
  $tmpAry[$row->parent_id][$row->id] = $row->name;
}
 
sortCategories($tmpAry, $ary, 0, "");

function sortCategories(&$inAry, &$outAry, $level, $indent)  {
  if( is_array($inAry[$level]) )  {
    while( list($id, $name) = each($inAry[$level]) ) {
      $outAry[$id] = "$indent $name";                 
       sortCategories($inAry, $outAry, $id, "$indent $name -- ");
    }
  }
}


This would result in the values of $ary looking something like this:

Colors
Colors -- Blue
Colors -- Green
Colors -- Green -- Light
Colors -- Red