开发者

An array for data of dropdown menu

There are some ideas for creating a dropdown menu from data populated from xml or json. But how can I do this purely with php? A possible method is to create a multi-level array. But what is the best way to create it from mysql data (having parent id 开发者_如何学Cfor sub-menus), and how to effectively read the array (via a foreach loop?)?


for php side, lets assume you retrieve using that query what is in the table in an array of format:

$menu = array(
   'page/1' => 'about',
   'page/2' => 'photos',
   'menu-title' =>  array('page/4' => 'sub-menu-1','page/5' => 'sub-menu-2')
);

echo '<ul>';
foreach($menu as $key => $value){
  if(is_string($value)){
     echo '<li><a href="'.$key.'">'.$value.'</a></li>';
  }
  if(is_array($value)){
    echo '<ul>';
    echo '<li><a href="#">'.key($value).'</a></li>';
    foreach($value as $sub_key => $sub_value){
      echo '<li><a href="'.$sub_key .'">'.$sub_value.'</a></li>';
    }
    echo '</ul>';
  }
}
echo '</ul>';

for mysql database, have a column of "parent_id" if it is null then it would be a root level, other than that, it would be a sub there, another column of "path" and "title,you can add a "weight" column as well to order them.

NOTE: this is untested code


I like to loop through the rows that are pulled from mysql and create an array where the key is the value for the input and the value is the text. So, if you wanted to create a dropdown like:

<input value="UT">Utah</input>
<input value="VT">Vermont</input>
<input value="NV">Nevada</input>
<input value="CA">California</input>

I would create an array that looked like this:

array(

       "UT" => "Utah",
       "VT" => "Vermont",
       "NV" => "Nevada",
       "CA" => "California",
)

It's very easy to translate the array into the html using a foreach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜