88855

PHP Dynamic Drop Down Menu

Question:

Here's the situation: I have a menu that needs to be created dynamically from the database. The menu hierarchy is determined by a 'parent' column in the table (each entry has one parent or NULL if it is only a parent)

The problem is that I can't think of how I would dynamically do this, considering I need proper <ul><li><ul><li> structure for my drop-down menu. This requires that I have my 'foreach' of child pages, within the foreach of parent pages? If that makes sense, is there a solution?

FYI: The array I am working with returns:

array(31) { [0]=> array(5) { ["id"]=> string(2) "31" ["title"]=> string(4) "Home" ["linkable"]=> string(1) "1" ["parent"]=> NULL ["override"]=> string(1) " " } [1]=> array(5) { ["id"]=> string(2) "30" ["title"]=> string(11) "Shop Online" ["linkable"]=> string(1) "1" ["parent"]=> string(2) "31" ["override"]=> string(4) "shop" } and on and on.

Answer1:

You need to write a recursive function to do this and have it call itself. I haven't tested this out, but I think it should get you started. I wouldn't endorse this function's efficiency since it runs through every item in the array and does a comparison even though you're going to only need an item or two from each run (likely).

PHP:

$arr = array(...); function output_lis($parentID = NULL){ global $arr; $stack = array(); //create a stack for our <li>'s foreach($arr as $a){ $str = ''; //if the item's parent matches the parentID we're outputting... if($a['parent']===$parentID){ $str.='<li>'.$a['title']; //Pass this item's ID to the function as a parent, //and it will output the children $subStr = output_lis($a['id']); if($subStr){ $str.='<ul>'.$subStr.'</ul>'; } $str.='</li>'; $stack[] = $str; } } //If we have <li>'s return a string if(count($stack)>0){ return join("\n",$stack); } //If no <li>'s in the stack, return false return false; }

Then output this on your page. Something like:

<ul> <?php echo output_lis(); ?> </ul>

Here is my sample array:

$arr = array( array('title'=>'home','parent'=>NULL,'id'=>1), array('title'=>'sub1','parent'=>1,'id'=>2), array('title'=>'sub2','parent'=>1,'id'=>3), array('title'=>'about us','parent'=>NULL,'id'=>4), array('title'=>'sub3','parent'=>4,'id'=>5), array('title'=>'sub4','parent'=>4,'id'=>6), );

Answer2:

No recursion necessary.

$parents = array(); $noparents = array(); foreach ($results as $ar) { if ( $ar['parent'] != NULL ) { $parents[$ar['parent']] = array(); array_push($parents[$ar['parent']], $ar['title']); } else { array_push($noparents, $ar['title']); } }

Now you have all of your links that belong to a parent listed in an array named after the parent. Your other links are in a separate array. You can join them if you like.

Extend it as is required for your application.

Recommend

  • WordPress > setting permalink option via script buggy?
  • Installing Perl6 and Panda on Ubuntu 15.10. Problems with bootstrap.pl
  • Can my PDF ping my server when it is opened?
  • Retrieving specified columns from a list of csv files to create a data data frame in R
  • Filter strings with regex before casting to numeric
  • Do I need to seed any random number generator before using EVP_PKEY_keygen of OpenSSL?
  • JqueryMobile Popup menu is not working
  • C# program and C++ DLL compiled for 32-bit system crash on 64-bit system
  • Android full screen on only one activity?
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Display issues when we change from one jquery mobile page to another in firefox
  • Accessing IRQ description array within a module and displaying action names
  • Get object from AWS S3 as a stream
  • Date difference with leap year
  • Excel - Autoshape get it's name from cell (value)
  • Check if a string to interpolate provides expected placeholders
  • Fill an image in a square container while keeping aspect ratio
  • How to set my toolbar fixed while scrolling android
  • To display the title for the current loaction in map in iphone
  • Rearranging Cells in UITableView Bug & Saving Changes
  • RestKit - RKRequestDelegate does not exist
  • AT Commands to Send SMS not working in Windows 8.1
  • Traverse Array and Display in markup
  • Matrix multiplication with MKL
  • How to delete a row from a dynamic generate table using jquery?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • trying to dynamically update Highchart column chart but series undefined
  • Benchmarking RAM performance - UWP and C#
  • Hits per day in Google Big Query
  • Angular 2 constructor injection vs direct access
  • How to stop GridView from loading again when I press back button?
  • File not found error Google Drive API
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • Sorting a 2D array using the second column C++
  • Reading document lines to the user (python)
  • Converting MP3 duration time