Tuesday, May 26, 2009

PHP OrgChart

last night, there's somebody add me at YM. asking for help. need to build simple org chart using PHP.

at 1st, i just give him a url tutorial from mysql dev at http://dev.mysql.com/tech-resources/articles/hierarchical-data.html to get some basic idea how to build simple but dynamic orgchart.

normaly i done this using perl, but i decide to take a try to write this using php...

here the result... hahha i manage to build basic engine with only basic structure/position of chart. i let him proceed with the code... hopefully it'll help him solve hihs problem..

and here the PHP code:

 
 
 $query  = "
SELECT node.*
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND parent.name = 'ELECTRONICS'
ORDER BY node.lft;


 ";
 
 $users = Array();
 $result = mysql_query($query);
 while($row = mysql_fetch_array($result, MYSQL_ASSOC))
 {
  $users[$row['parent']][] =  $row['category_id'] . "|"  . $row['name'];
 }
 
 
 
 function recursive($parent,$array)
 { 
  $pcount = count($array[$parent]);
        
  for ($u = 0; $u < $pcount; $u++) {  
   list($id, $name) = split('\|', $array[$parent][$u]);
   $count = count($array[$id]);
   if($count > 0){
    echo "";
    echo ""; 
    echo ""; 
    recursive($id,$array);
    echo "
$name
|
"; }else{ echo "
$name
"; } } } echo ""; recursive(0,$users); echo "
";

and here the sql code:

CREATE TABLE IF NOT EXISTS `nested_category` (
 `category_id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(20) NOT NULL,
 `lft` int(11) NOT NULL,
 `rgt` int(11) NOT NULL,
 `parent` int(11) NOT NULL,
 PRIMARY KEY (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

--
-- Dumping data for table `nested_category`
--

INSERT INTO `nested_category` (`category_id`, `name`, `lft`, `rgt`, `parent`) VALUES
(1, 'ELECTRONICS', 1, 20, 0),
(2, 'TELEVISIONS', 2, 9, 1),
(3, 'TUBE', 3, 4, 2),
(4, 'LCD', 5, 6, 2),
(5, 'PLASMA', 7, 8, 2),
(6, 'PORTABLE ELECTRONICS', 10, 19, 1),
(7, 'MP3 PLAYERS', 11, 14, 6),
(8, 'FLASH', 12, 13, 7),
(9, 'CD PLAYERS', 15, 16, 6),
(10, '2 WAY RADIOS', 17, 18, 6);

And Css:

.parentnode{
 margin: 5px;
 position: relative;
 width: 200px;
 text-align : center;
 border: 1px solid #ffcc33;  
 padding: 10px;
}
.childnode{
 margin: 5px;
 position: relative;
 width: 200px;
 text-align : center;
 border: 1px solid #000000; 
 padding: 10px;
}

i make some changes from MySQL Dev tutorial... as using parent child column make it easier to construct the chart. and lft & rgt column make it easier/faster to query/select required row/wing.

happy coding..

No comments: