1

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 for sub-menus), and how to effectively read the array (via a foreach loop?)?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I tested it, and it is perfect. THANKS!
0

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.

2 Comments

You considered it as a dropdown form, but I am referring to a menu list as <ul><li><ul> ..... and the problem is how to list child items.
this will not create dropdown you need to used select for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.