<?php
$elems = array(
array( 'id' => 1, 'pid' => 0, 'title' => '1' ),
array( 'id' => 2, 'pid' => 1, 'title' => '2' ),
array( 'id' => 3, 'pid' => 1, 'title' => '3' ),
array( 'id' => 4, 'pid' => 3, 'title' => '4' ),
array( 'id' => 5, 'pid' => 0, 'title' => '5' ),
array( 'id' => 6, 'pid' => 5, 'title' => '6' ),
array( 'id' => 7, 'pid' => 5, 'title' => '7' ),
array( 'id' => 8, 'pid' => 5, 'title' => '8' ),
array( 'id' => 9, 'pid' => 0, 'title' => '9' ),
);
$links = array();
$tree = array();
for( $q = 0; $q < count( $elems ); $q++ )
{
$elem = $elems[$q];
if( $elem['pid'] === 0 )
{
$tree[$elem['id']] = $elem;
$links[$elem['id']] = &$tree[$elem['id']];
}
else
{
$links[$elem['pid']]['childrens'][$elem['id']] = $elem;
$links[$elem['id']] = &$links[$elem['pid']]['childrens'][$elem['id']];
}
}
echo '<pre>';
print_r( $tree );
echo '</pre>';
?>