PHP MySQL Multilevel Menu dengan Single Query

Discussion in 'Desain Web dan Programming' started by PusatHosting, 31 Dec 2014.

Thread Status:
Not open for further replies.
  1. PusatHosting

    PusatHosting Hosting Guru Web Hosting

    Messages:
    3,343
    Likes Received:
    326
    Trophy Points:
    83
    Ini saya temukan script php code multilevel menu dengan single Query karena agak susah nyarinya kemarin maka itu saya duplikasi postingnya disini supaya lebih banyak ter-index nya dan lebih mudah ditemukan.

    Script php multilevel menu memang banyak samplenya tapi rata-rata looping memanggil query mysql berkali-kali dan saya rasa pemborosan.

    Ini kodenya,

    Code:
      // Select all entries from the menu table
      $result=mysql_query("SELECT id, label, link, parent FROM menu ORDER BY parent, sort, label");
      // Create a multidimensional array to conatin a list of items and parents
      $menu = array(
      'items' => array(),
      'parents' => array()
      );
      // Builds the array lists with data from the menu table
      while ($items = mysql_fetch_assoc($result))
      {
      // Creates entry into items array with current menu item id ie. $menu['items'][1]
      $menu['items'][$items['id']] = $items;
      // Creates entry into parents array. Parents array contains a list of all items with children
      $menu['parents'][$items['parent']][] = $items['id'];
      }
    
    Dan ini adalah menu buildernya
    Code:
      // Menu builder function, parentId 0 is the root
      function buildMenu($parent, $menu)
      {
      $html = "";
      if (isset($menu['parents'][$parent]))
      {
      $html .= "
      <ul>\n";
      foreach ($menu['parents'][$parent] as $itemId)
      {
      if(!isset($menu['parents'][$itemId]))
      {
      $html .= "<li>\n <a href='".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a>\n</li> \n";
      }
      if(isset($menu['parents'][$itemId]))
      {
      $html .= "
      <li>\n <a href='".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a> \n";
      $html .= buildMenu($itemId, $menu);
      $html .= "</li> \n";
      }
      }
      $html .= "</ul> \n";
      }
      return $html;
      }
      echo buildMenu(0, $menu);
    
    Kode diatas sudah saya coba dan berjalan lancar, jadi selamat mencoba.

    Sumber : http://wizardinternetsolutions.com/articles/web-programming/single-query-dynamic-multi-level-menu
     
    pluto01 likes this.
  2. pluto01

    pluto01 Hosting Guru Web Hosting

    Messages:
    3,692
    Likes Received:
    757
    Trophy Points:
    113
    thanks mas, izin tandai dlu sapa tahu bs jd referensi jika dibutuhkan kedepannya
     
    PusatHosting likes this.
Loading...
Thread Status:
Not open for further replies.

Share This Page

Loading...