TShopping

 找回密碼
 註冊
搜索
查看: 1136|回復: 0

[教學] 用PHP建立動態多層導覽列 Create a dynamic menu in PHP

[複製鏈接]
發表於 2017-3-10 08:05:08 | 顯示全部樓層 |閱讀模式
 
Push to Facebook Push to Plurk  
The creation of a dynamic menu with a nested un-ordered list without using any JavaScript code is sometimes a problem because the script needs to “remember” the values, sub values and also the query string from previous clicked links. In this tutorial I will explain how to create a dynamic navigation menu using PHP and MySQ. While using standard HTML elements (un-ordered lists) it’s easy to add different CSS styles later. Follow this link for a demonstration example or download the PHP example files here.
First I need a database table holding the information for our navigation menu:

建立動態多層導覽列,如巢狀 OPENCART的導覽列,沒有使用任何的JavaScript會有點問題,因為必須"記得" 值,副值和查詢預先的連結,在這個教學中我來介紹如何用PHP及MYSQL建立動態多層導覽列,用簡單的HTML及CSS就可以了

  1. CREATE TABLE `dyn_menu` (
  2.   `id` int(11) NOT NULL auto_increment,
  3.   `label` varchar(50) NOT NULL default '',
  4.   `link_url` varchar(100) NOT NULL default '#',
  5.   `parent_id` int(11) NOT NULL default '0',
  6.   PRIMARY KEY  (`id`)
  7. ) TYPE=MyISAM;
複製代碼

Create a dynamic menu in PHP from your MySQL data先在MYSQL建立TABLE如上面代碼
Next I have to add some data for our PHP menu: menu items and sub-menu items.
在PHP檔案加入一些代碼如下
Example: The menu item “Products” will have several sub-menu items and the record id is a “2”
舉例:MENU物件“Products”可能有多個sub-menu物件,id是“2”
All sub-menu items need the number “2” as value for the parent_id. The parent_id for each main menu item is a “0” (zero).
所有sub-menu物件需要在parent_id號碼為 “2”的值
如果parent_id值為“0” (zero),這就是主MENU上物件
In the following code block I create a database result set and I add the value into a multi-dimensional arrays: $parent_menu and $sub_menu
在資料庫內我加入多維陣列:有$parent_menu and $sub_menu變數
The $parent_menu array is holding the label, the link (URL) and a count value that I need to decide if there is a sub-item or not. The $sub_menu array is holding the label and link values and the value of the parent_id.
$parent_menu array就是主標籤(如分類項)、URL和數值,我可以決定是否為附屬項目,$sub_menu array標籤(如附屬項)、URL和數值依附在parent_id
I “loop” through the database result set to test each record’s parent_id is a zero (0) or not. If the value equal to “0” it’s a parent record and otherwise it becomes a sub-item record.
從資料庫條件用迴圈來截取parent_id紀錄是否為0,如果parent_id為0就是主項,其他則為附屬項
  1. <?php
  2. $parent_menu = array();
  3. $sub_menu = array();
  4. $db = new mysqli('localhost', 'db_user', 'db_password', 'db_name')) {
  5. $items = $db->("SELECT id, label, link_url, parent_id FROM dyn_menu ORDER BY parent_id, id ASC");
  6. while ($obj = $items->fetch_object()) {
  7.     if ($obj->parent_id == 0) {
  8.         $parent_menu[$obj->id]['label'] = $obj->label;
  9.         $parent_menu[$obj->id]['link'] = $obj->link_url;
  10.     } else {
  11.         $sub_menu[$obj->id]['parent'] = $obj->parent_id;
  12.         $sub_menu[$obj->id]['label'] = $obj->label;
  13.         $sub_menu[$obj->id]['link'] = $obj->link_url;
  14.         if (empty($parent_menu[$obj->parent_id]['count'])) {
  15.             $parent_menu[$obj->parent_id]['count'] = 0;
  16.         }
  17.         $parent_menu[$obj->parent_id]['count']++;
  18.     }
  19. }
  20. $items->close();
  21. $db->close();
複製代碼

Put all the PHP code into a single function
把PHP代碼複製到檔案
For the creation of the whole navigation bar I a custom function, this way it’s more portable and I can access the code several times in different scripts without to write the code all over again.
用自製的function建立導覽列,我可能從多次不同的代碼獲取不同的值,直到全部完成
  1. function dyn_menu($parent_array, $sub_array, $qs_val = 'menu', $main_id = 'nav', $sub_id = 'subnav', $extra_style = 'foldout') {
  2.     $menu = '
  3.     <ul id="'.$main_id.'">';
  4.     foreach ($parent_array as $pkey => $pval) {
  5.         if (!empty($pval['count'])) {
  6.             $menu .= '
  7.         <li><a class="'.$extra_style.'" href="'.$pval['link'].'?'.$qs_val.'='.$pkey.'">'.$pval['label'].'</a></li>';
  8.         } else {
  9.             $menu .= '
  10.         <li><a href="'.$pval['link'].'">'.$pval['label'].'</a></li>';
  11.         }
  12.         if (!empty($_REQUEST[$qs_val])) {
  13.             $menu .= '
  14.         <ul id="'.$sub_id.'">';
  15.             foreach ($sub_array as $sval) {
  16.                 if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) {
  17.                     $menu .= '
  18.             <li><a href="'.rebuild_link($sval['link'], $qs_val, $sval['parent']).'">'.$sval['label'].'</a></li>';
  19.                 }
  20.             }
  21.             $menu .= '
  22.         </ul>';
  23.         }
  24.     }
  25.     $menu .= '
  26.     </ul>';
  27.     return $menu;
  28. }
複製代碼


The arguments of the function are both arrays, the name of the query string value that’s used to fold out the menu, the two ids used to identify the un-ordered lists with the CSS style and an extra name for some CSS pseudo class to give a main link element with sub-items a different look. A nested un-ordered list is a list with list items (“li” elements) and several other lists (“ul” elements). A main node can hold another lists or new “ul” elements.
To do this I start in my function with a “ul” element, to identify the element with CSS we add some id attribute here.
函數的參數都是數組,用於折疊菜單的查詢字符串值的名稱,用於標識具有CSS樣式的未排序列表的兩個ID,以及一些CSS偽的額外名稱 一個主項目與次項目有不同的外觀及位置。 所以用列表項(“li”元素)和其他列表用(“ul”元素)。 主節點可以保存另一個列表或新的“ul”元素。
一開始CSS用一個“ul”元素

  1. foreach ($parent_array as $pkey => $pval) {
  2.     if (!empty($pval['count'])) {
  3.         $menu .= '
  4.         <li><a class="'.$extra_style.'" href="'.$pval['link'].'?'.$qs_val.'='.$pkey.'">'.$pval['label'].'</a></li>';
  5.     } else {
  6.         $menu .= '
  7.         <li><a href="'.$pva['link'].'">'.$pval['label'].'</a></li>';
  8.     }
複製代碼



Inside the loop there is a test for the count value from parent items, if the count is not null the menu item query string value is added.
在迴圈裡會選出 parent 值(主項),其他的則為附屬項


  1. if (!empty($_REQUEST[$qs_val])) {
  2.     $menu .= '
  3.         <ul id="'.$sub_id.'">';
  4.     foreach ($sub_array as $sval) {
  5.         if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) {
  6.             $menu .= '
  7.             <li><a href="'.rebuild_link($sval['link'], $qs_val, $sval['parent']).'">'.$sval['label'].'</a></li>';
  8.         }
  9.     }
  10.     $menu .= '
  11.         </ul>';
  12.     }
複製代碼

A PHP function which is used to manipulate the query string
查詢字串用 PHP function  
The code block begins with a test for $_GET variable which is posted via the link from the parent menu item a new loop is opened to create a list with sub-items related to the parent item. Inside the statement the function rebuild_link() is called, a function which is used to manipulate the query string:
這測試代碼通過用 $_GET變數來找到迴圈內的菜單主項內的附屬項
rebuild_link()裡面詳述操作代碼

  1. function rebuild_link($link, $parent_var, $parent_val) {
  2.     $link_parts = explode('?', $link);
  3.     $base_var = '?'.$parent_var.'='.$parent_val;
  4.     if (!empty($link_parts[1])) {
  5.         $link_parts[1] = str_replace('&', '##', $link_parts[1]);
  6.         $parts = explode('##', $link_parts[1]);
  7.         $newParts = array();
  8.         foreach ($parts as $val) {
  9.             $val_parts = explode('=', $val);
  10.             if ($val_parts[0] != $parent_var) {
  11.                 array_push($newParts, $val);
  12.             }
  13.         }
  14.         if (count($newParts) != 0) {
  15.             $qs = '&'.implode('&', $newParts);
  16.         }
  17.         return $link_parts[0].$base_var.$qs;
  18.     } else {
  19.         return $link_parts[0].$base_var;
  20.     }
  21. }
複製代碼

The arguments for this function are the link from the array, the variable name and value from the parent menu item (to keep the list open). Inside the function the query string will be exploded and is getting rebuilt without becoming in trouble with existing parts or new variables. At the end, the function will return a modified link with all parts of the query string.
function array內的參數,變數名稱及值都從主菜單物件擷取,如果function寫出有BUG可能就回變成無窮迴圈
Example PHP dynamic menu usage
呼叫動態菜單
How to use this dynamic menu PHP function? It’s easy just echo the function name  with all the function attributes:

  1. echo dyn_menu($parent_menu, $sub_menu, 'menu', 'nav', 'subnav');
複製代碼

Don’t forget to try the PHP menu demo for a better understanding.
不要忘記到上述連結多多閱讀

參考文章
http://www.web-development-blog.com/archives/dynamic-menu-in-php/


 

臉書網友討論
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2019-12-16 07:43 , Processed in 0.055965 second(s), 21 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表