Read 326 times | Created 2013-04-03 15:57:27 | Updated 2014-07-01 08:04:13 | | |

 

<?php
/*************************
// GENERATED NESTED LIST
// created by   : Cahya DSN
// created date : 2012-09-14
// updated date : 2013-04-04
**************************
USE `test`;  

DROP TABLE IF EXISTS `project`;  
CREATE TABLE IF NOT EXISTS `project` (  
 `id_task` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key untuk table project',  
 `id_parenttask`  int(11) unsigned NOT NULL DEFAULT 0,
 `task_name` varchar(30) NOT NULL COMMENT 'nama task',
 `task_desc` text COMMENT 'deskripsi task',
 `status` tinyint(4) unsigned NOT NULL DEFAULT 0,  
 PRIMARY KEY(`id_task`)  
) ENGINE=MyISAM COMMENT='tabel untuk menyimpan data project';  

INSERT INTO `project`(`id_task`,`id_parenttask`,`task_name`,`task_desc`,`status`) VALUES  
(NULL,0,'Kategori 1','',0),  
(NULL,1,'Kategori 1.1','',0),  
(NULL,1,'Kategori 1.2','',0),  
(NULL,3,'Kategori 1.2.1','',0),  
(NULL,0,'Kategori 2','',0),  
(NULL,0,'Kategori 3','',0),  
(NULL,6,'Kategori 3.1','',0),  
(NULL,6,'Kategori 3.2','',0),  
(NULL,3,'Kategori 1.2.2','',0),  
(NULL,6,'Kategori 3.3','',0);  
*/
function GenerateDataArray($arr, $parent = 0)
{
    $pages = Array();
    foreach($arr as $page)
    {
        if($page['id_parenttask'] == $parent)
        {
            $page['sub'] = isset($page['sub']) ? $page['sub'] : GenerateDataArray($arr, $page['id_task']);
            $pages[] = $page;
        }
    }
    return $pages;
}

// loop the multidimensional array recursively to generate the HTML
function GenerateDataHTML($nav)
{
    $html = '';
    foreach($nav as $page)
    {
        $html .= "<ul>\n<li>\n";
        $html .= '<a href="' . $page['id_task'] . '">' . $page['task_name'] . '</a>';
        $html .= GenerateDataHTML($page['sub']);
        $html .= "</li>\n</ul>\n";
    }
    return $html;
}
//database configuration  
$dbhost='localhost';  
$dbuser='root';  
$dbpass='';  
$dbname='test';  
//database connection  
$db=new mysqli($dbhost,$dbuser,$dbpass,$dbname);  
//query to get project datas from database   
$sql="SELECT * FROM project";  
$data=array();
$result=$db->query($sql);  
while($records=$result->fetch_assoc()){  
  $data[]=$records;  
}
$result->close();
$db->close();
/* DUMMY DATA FOR TEST
//======================
$data=array(
array('id_task'=>1,'task_name'=>'Kategori 1','id_parenttask'=>0),
array('id_task'=>2,'task_name'=>'Kategori 1.1','id_parenttask'=>1),
array('id_task'=>3,'task_name'=>'Kategori 1.2','id_parenttask'=>1),
array('id_task'=>4,'task_name'=>'Kategori 1.2.1','id_parenttask'=>3),
array('id_task'=>5,'task_name'=>'Kategori 2','id_parenttask'=>0),
array('id_task'=>6,'task_name'=>'Kategori 3','id_parenttask'=>0),
array('id_task'=>7,'task_name'=>'Kategori 3.1','id_parenttask'=>6),
array('id_task'=>8,'task_name'=>'Kategori 3.2','id_parenttask'=>6)
);
*/

$dataarray = GenerateDataArray($data);
echo GenerateDataHTML($dataarray);