PHPBuilder - Sorting a hierarchial listing for pulldowns.

RSS Twitter

Sorting a hierarchial listing for pulldowns.

by: Philip Halsltrom
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 -- Blue
Colors -- Green
Colors -- Green -- Light
Colors -- Red

Comment and Contribute

Your comment has been submitted and is pending approval.

Philip Halsltrom



(Maximum characters: 1200). You have characters left.