cdsatrian

generate nested list

Sep 14th, 2012
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.59 KB | None | 0 0
  1. <?php
  2. /*************************
  3. // GENERATED NESTED LIST
  4. // created by   : Cahya DSN
  5. // created date : 2012-09-14
  6. **************************/
  7. function GenerateDataArray($arr, $parent = 0)
  8. {
  9.     $pages = Array();
  10.     foreach($arr as $page)
  11.     {
  12.         if($page['parent'] == $parent)
  13.         {
  14.             $page['sub'] = isset($page['sub']) ? $page['sub'] : GenerateDataArray($arr, $page['id_category']);
  15.             $pages[] = $page;
  16.         }
  17.     }
  18.     return $pages;
  19. }
  20.  
  21. // loop the multidimensional array recursively to generate the HTML
  22. function GenerateDataHTML($nav)
  23. {
  24.     $html = '';
  25.     foreach($nav as $page)
  26.     {
  27.         $html .= '<ul><li>';
  28.         $html .= '<a href="' . $page['link'] . '">' . $page['title'] . '</a>';
  29.         $html .= GenerateDataHTML($page['sub']);
  30.         $html .= '</li></ul>';
  31.     }
  32.     return $html;
  33. }
  34. $data=array(
  35. array('id_category'=>1,'title'=>'Kategori 1','parent'=>0,'link'=>'#','sort'=>1),
  36. array('id_category'=>2,'title'=>'Kategori 1.1','parent'=>1,'link'=>'#','sort'=>1),
  37. array('id_category'=>3,'title'=>'Kategori 1.2','parent'=>1,'link'=>'#','sort'=>2),
  38. array('id_category'=>4,'title'=>'Kategori 1.2.1','parent'=>3,'link'=>'#','sort'=>1),
  39. array('id_category'=>5,'title'=>'Kategori 2','parent'=>0,'link'=>'#','sort'=>2),
  40. array('id_category'=>6,'title'=>'Kategori 3','parent'=>0,'link'=>'#','sort'=>3),
  41. array('id_category'=>7,'title'=>'Kategori 3.1','parent'=>6,'link'=>'#','sort'=>1),
  42. array('id_category'=>8,'title'=>'Kategori 3.2','parent'=>6,'link'=>'#','sort'=>2)
  43. );
  44. $dataarray = GenerateDataArray($data);
  45. echo GenerateDataHTML($dataarray);
Add Comment
Please, Sign In to add comment