This should be very basic, but I am a little stumped!
Here is my array:
$menu = array(
'Home',
'Stuff'=>array(
'Losta Stuff',
'Less Stuff',
'Ur moms stuff',
'FAQ'
),
'Public Works'
);
Here is my logic:
echo "<ol>
";
foreach( (array)$menu as $header )
{
echo ' <li><b>'.$header."</b><br />
";
echo ' <ol>';
foreach( (array)$header as $headers )
{
echo ' <li>'.$headers.".</li>
";
}
echo ' </ol>';
}
echo "</ol>
";
As you can see, Home and Public Works don't have data in the them, so I get a
Warning: Invalid argument supplied for foreach() in test.php on line ##
If I add (array)
to $header
like this: foreach( (array)$header as $headers )
, It no longer gives me the error, but it just displays the $header
as the $headers
(i.e. Home - Home, Instead of Home - nothing).
Basically, if the data is empty, I want it to do nothing!
You should test for whether or not the current item that you're trying to echo
is an array, which can be done with is_array
, and then act accordingly. Something like the following might do the trick.
<?php
$menu = array(
'Home',
'Stuff'=>array(
'Losta Stuff',
'Less Stuff',
'Ur moms stuff',
'FAQ'
),
'Public Works'
);
echo "<ol>
";
foreach($menu as $menuName => $header )
{
if (!is_array($header))
{
echo ' <li><b>'.$header."</b><br />
";
}
else
{
echo "<li><b>$menuName</b><ol>";
foreach($header as $headers )
{
echo ' <li>'.$headers.".</li>
";
}
echo "</ol></li>";
}
}
echo "</ol>
";
I see something like this:
// your old menu was using keys for headers on "submenus" only
// this one uses keys for headers for everything
$menu = array(
'Home'=>'Home',
'Stuff'=>array(
'Losta Stuff',
'Less Stuff',
'Ur moms stuff',
'FAQ'
),
'Public Works' => 'Public Works',
);
echo "<ol>
";
foreach( (array)$menu as $header => $items )
{
echo ' <li><b>'.$header."</b>";
if (is_array($items)) {
echo "<br />
";
echo ' <ol>';
foreach( $items as $subhead )
{
echo ' <li>'.$subhead.".</li>
";
}
echo ' </ol>';
}
}
echo "</ol>
";
Using is_array to determine if there are more options underneath the current menu.