PDA

View Full Version : Building a menu from an array: Double Values Appear


Kurashu
02-25-2005, 03:12 AM
I've constructed a function that will build a list-menu from an array. However, the only problem with it is that it repeats the values from the array twice (exhibited here (http://dev.greenbomber.com/funct2.php))

Here is the code I am using:

<?php

function build_menu($menu, $base=false)
{
if(!is_array($menu)) { return false; }

$string = '<ul class="menu">' . "\n\r";
foreach($menu as $k=>$v)
{
foreach($v as $key=>$value)
{
$string .= sprintf('<li><a href="%2$s" title="%1$s">%1$s</a></li>' . "\n\r", $menu[$k]['title'], ( $base ? $base . $menu[$k]['url'] : $menu[$k]['url'] ));
}
}
$string .= '</ul>';
return $string;
}
$menu = array(
array('title' => 'Lyrics', 'url' => 'lyrics.php'),
array('title' => 'Archives', 'url' => 'archive.php'),
array('title' => 'Index', 'url' => 'index.php'),
);
echo build_menu($menu, 'http://www.greenbomber.com/');
?>

firepages
02-25-2005, 04:22 AM
you don't need the inner loop , it currently does nothing.

<?
foreach($menu as $k=>$v)
{
$string .= sprintf('<li><a href="%2$s" title="%1$s">%1$s</a></li>' . "\r\n", $menu[$k]['title'], ( $base ? $base . $menu[$k]['url'] : $menu[$k]['url'] ));
}
$string .= '</ul>';
return $string;
}
?>