|
Posted by Toby A Inkster on 12/07/07 12:47
Arne-Kolja Bachstein wrote:
> An array out of a database with fields PageID and Title. The PageID
> field is a string like "1.1.1", association a menu like
>
> 1.1.1 (Menu 1, Sub 1, Entry 1)
> 1.1.2 (Menu 1, Sub 1, Entry 2)
> 1.2.1 (...)
> 2.1.1
> 3.1.1
> 3.1.2
<?php
// OK, Here's your input array:
$menu = array(
array('1', 'Fish'),
array('1.1', 'Cod'),
array('1.2', 'Sardines'),
array('1.3', 'Shark'),
array('1.3.1', 'Hammerhead'),
array('1.3.2', 'Great White'),
array('1.4', 'Haddock'),
array('2', 'Dogs'),
array('2.1', 'Bulldog'),
array('2.2', 'Poodle'),
array('3', 'Cats'),
array('3.0', 'Cheetah'),
array('3.1', 'Puma'),
array('3.2', 'Jaguar'),
array('3.3', 'Panther'),
array('3.4', 'Tiger'),
array('3.4.1', 'Toyger'),
array('3.5', 'Leopard')
);
// Now let's get it into a more useful format:
$_menu = array();
foreach ( $menu as $item )
{
list($id, $title) = $item;
$address = '$_menu['.str_replace('.', '][', $id)."]";
$title = str_replace("\'", "\\\'", $title);
eval("$address"."['title'] = '$title';\n");
eval("$address"."['id'] = '$id';\n");
}
// Define a recursive function to print this menu:
function html_menu ($menu, $indent='')
{
$rv = '';
if ( !is_array($menu) )
return '';
if (isset($menu['title']))
$rv = $indent . sprintf('<li><a href="index.php?id=%s">%s</a>',
htmlentities($menu['id']),
htmlentities($menu['title']));
if ( count($menu) > 2 )
{
$rv .= "\n"
. "$indent\t<ul>\n";
foreach ($menu as $k=>$submenu)
if (preg_match('/^[0-9]+$/', $k))
$rv .= html_menu($submenu, "$indent\t\t");
$rv .= "$indent\t</ul>\n";
if (isset($menu['title']))
$rv .= "$indent</li>\n";
}
else
{
$rv .= "</li>\n";
}
return $rv;
}
// Use recursive function to print out menu:
print html_menu($_menu);
?>
--
Toby A Inkster BSc (Hons) ARCS
[Geek of HTML/SQL/Perl/PHP/Python/Apache/Linux]
[OS: Linux 2.6.17.14-mm-desktop-9mdvsmp, up 12 days, 18:39.]
Sharing Music with Apple iTunes
http://tobyinkster.co.uk/blog/2007/11/28/itunes-sharing/
Navigation:
[Reply to this message]
|