View Single Post
Old 27-Feb-2007, 09:10 PM   #2 (permalink)
Sangeetha
Fixed Error!
 
Sangeetha's Avatar

Posts: 139
Location: Chennai
Join Date: Feb 2007
Rep Power: 2 Sangeetha is on a distinguished road

IM:
Default Re: Sorting MySQL Results

Update. Here's a version that puts it into a select: Adjacency Table to Hierarchy | riceball

<?php
$menu = array();
$menu[] = array( 'id' => 1, 'parent_id' => 0, 'name' => 'a' );
$menu[] = array( 'id' => 2, 'parent_id' => 1, 'name' => 'a.1' );
$menu[] = array( 'id' => 3, 'parent_id' => 0, 'name' => 'b' );
$menu[] = array( 'id' => 4, 'parent_id' => 3, 'name' => 'b.1' );
$menu[] = array( 'id' => 5, 'parent_id' => 3, 'name' => 'b.2' );
$menu[] = array( 'id' => 6, 'parent_id' => 5, 'name' => 'b.2.1' );

// acts like a SELECT statement
function selectWhereParentIdIs( $id )
{
global $menu;
$out = array();

for( $i=0; $i<count($menu); $i++ )
{
if ($menu[$i]['parent_id']==$id)
$out[] = $menu[$i];
}
return $out;
}


function menuToSelect( $id, $depth )
{
$ar = selectWhereParentIdIs( $id );
if ( count($ar) > 0 )
{
reset( $ar );
foreach( $ar as $value )
{
$out .= '<option>';
if ($depth>0) $out .= '-';
$out .= str_repeat( '-', $depth ) . $value['name'];
$out .= '</option>';
$out .= menuToSelect( $value['id'], $depth+1 );
}
return $out;
}
else
{
return '';
}

}

echo '<form><select>';
echo menuToSelect( 0, 0 );
echo '</select>';

?>
Sangeetha is offline   Reply With Quote