PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Has anybody some idea in generating proper <li><ul> tags for the fields so that it becomes as above ..
Note it can be n level deep.
Thanks in advance for any tips and suggestions.
/* Roughly speaking we want to map item id's to titles and children:
array(
1 => array(
'title' => 'Item One',
'children' => array(
3 => array('title' => 'Sub Item One', 'children' => array())
)
),
2 => array('title' => 'Item 2', 'children' => array())
)
*/
/**
* Recursively fetch branches in the menu starting with $parent_id.
* @param int $parent_id
* @return array
*/
function get_menu_array($parent_id = 0)
{
$array = array();
$sql = 'SELECT * FROM menu WHERE parent_id = ' . ((int) $parent_id);
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$array[$row['id']] = array('title' => $row['title'], 'children' => get_menu_array($row['parent_id']));
}
return $array;
}
/**
* Build a recursive tree menu using the given array.
* @param array $array
* @return string
*/
function menu_to_string($array)
{
$ret = '<ul>';
foreach ($array as $details)
{
$ret .= '<li>' . $details['title'];
if (!empty($details['children']))
{
//Recurse
$ret .= menu_to_string($details['children']);
}
$ret .= '</li>';
}
$ret .= '</ul>';
return $ret;
}
//Display it
echo menu_to_string(get_menu_array());
It's possible to do without the recursion but it's possibly not worth it if there's no signifcant slowdown. It's a lot harder to write and a lot harder to read without the recursion though.
but it should be as per above html...no <ul> tags ar first...I think if from the returned value if we ommitted first <ul> and last </ul> tag..it would work fine..
Thanks for the help again..