Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- --
- -- Database: `test`
- --
- -- --------------------------------------------------------
- --
- -- Table structure for table `nested_categories`
- --
- DROP TABLE IF EXISTS `nested_categories`;
- CREATE TABLE IF NOT EXISTS `nested_categories` (
- `id_cat` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(20) NOT NULL,
- `lft` int(11) NOT NULL,
- `rgt` int(11) NOT NULL,
- PRIMARY KEY (`id_cat`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
- --
- -- Dumping data for table `nested_categories`
- --
- INSERT INTO `nested_categories` (`id_cat`, `name`, `lft`, `rgt`) VALUES
- (1, 'Website', 1, 22),
- (2, 'Database', 2, 9),
- (3, 'Oracle', 3, 4),
- (4, 'MySQL', 5, 6),
- (5, 'SQL Server', 7, 8),
- (6, 'Programming', 10, 19),
- (7, 'JavaScript', 11, 14),
- (8, 'jQuery', 12, 13),
- (9, 'PHP', 15, 16),
- (10, 'CSS', 17, 18),
- (11, 'HTML', 20, 21);
- */
- mysql_connect('localhost','root','');
- mysql_select_db('test');
- $sql="SELECT node.name, (COUNT( parent.name ) -1) AS depth
- FROM nested_categories AS node
- CROSS JOIN nested_categories AS parent
- WHERE node.lft BETWEEN parent.lft AND parent.rgt
- GROUP BY node.name
- ORDER BY node.lft";
- $result = mysql_query($sql);
- $tree = array();
- while ($row = mysql_fetch_assoc($result)) {
- $tree[] = $row;
- }
- // Bootstrap loop
- $result = '';
- $currDepth = 0;
- $lastNodeIndex = count($tree) - 1;
- // Start the loop
- foreach ($tree as $index => $currNode) {
- // Level down? (or the first)
- if ($currNode['depth'] > $currDepth || $index == 0) {
- $result .= '<ul>';
- }
- // Level up?
- if ($currNode['depth'] < $currDepth) {
- $result .= str_repeat('</ul></li>', $currDepth - $currNode['depth']);
- }
- // Always open a node
- $t = ($index == 0) ? 1 : 2;
- $result .= '<li>' . $currNode['name'];
- // Check if there's chidren
- if ($index != $lastNodeIndex && $tree[$index + 1]['depth'] <= $tree[$index]['depth']) {
- $result .= '</li>'; // If not, close the <li>
- }
- // Adjust current depth
- $currDepth = $currNode['depth'];
- // Are we finished?
- if ($index == $lastNodeIndex) {
- $result .= '</ul>' . str_repeat('</li></ul>', $currDepth);
- }
- }
- // Indent the code
- // For UTF8: tidy_parse_string($result, array('indent' => true, 'show-body-only' => true), 'UTF8')
- //$result = tidy_parse_string($result, array('indent' => true, 'show-body-only' => true));
- print $result;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement