Jump to content

[SOLVED] Associative Information used for foreach in a menu in php


Aaron_Escobar

Recommended Posts

I everybody. I'm building dynamic php menu that requires for each menu item; a title, the url to go to, and the button's width.

 

Look at this code:

<?php
//Menu Items
$menuItem;
$menuItem["Menu Item1"] = "some_page.php";
$menuItem["Menu Item2"] = "another_page.php";
$menuItem["Menu Item3"] = "oh_look_another_page.php";

//For each variable, echo information
foreach( $menuItem as $key => $value){
echo "Name: $key, Link: $value <br />";
}
?>

As you can see, the variables being echoed have only two bits of information; the menu item's title, and the url to redirect. But I need to show a third bit of information: the button's width for each menu. Each button has a different width in the menu.

 

Does anybody know a better way with foreach? Maybe using associative arrays with multiple associatives?

I would do something like this:

 

<?php
//Menu Items
$menuItem;
$menuItem["Menu Item1"] = array("some_page.php", 120);
$menuItem["Menu Item2"] = array("another_page.php", 100);
$menuItem["Menu Item3"] = array("oh_look_another_page.php", 10);

//For each variable, echo information
foreach($menuItem as $karr => $arr){
     foreach($arr as $key => $value){
        echo "Name: $karr, Link: {$value[0]}, Width: {$value[1]}<br />";
     }
}
?>

By the way "The Little Guy", after testing, your code did not work. However, I did manage to edit and fix your version of my code. It goes as the following:

<?php
//Menu Items
//Note the syntax.

$menuItem;
$menuItem["Link 1"] = array("some_page.php", "100");
$menuItem["Link 2"] = array("some_page2.php", "50");

//Create the Header

//For each variable, echo information
foreach( $menuItem as $key => $value){
echo "Button Title: $key, Button Link: $value[0], Button width: $value[1]";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.