General Programming Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
User Name:
Password:
Remember me
 
Go Back   Dev Articles Community ForumsProgrammingGeneral Programming Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Display Modes
 
Unread Dev Articles Community Forums Sponsor:
  #1  
Old November 5th, 2002, 12:25 PM
Lindset Lindset is offline
weirdomoderator
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2002
Location: Alta, Norway
Posts: 370 Lindset User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 7
Send a message via ICQ to Lindset Send a message via AIM to Lindset
Quick Example: How to show something hierarchically (tree structure)

Here's another quick example.. hope you'll enjoy it.. here's a way to show categories hierachically.. I'm using a MySQL database in the exampe, so I guess I'll just start by giving you the table structure:

Code:
CREATE TABLE categories (
  id mediumint(11) unsigned NOT NULL auto_increment,
  name varchar(255) NOT NULL default '0',
  parent tinyint(11) unsigned NOT NULL default '0',
  PRIMARY KEY  (id)
) TYPE=MyISAM;


And here's some table data:

Code:
INSERT INTO categories (name, parent) VALUES("Category 1", "0");
INSERT INTO categories (name, parent) VALUES("Category 2", "0");
INSERT INTO categories (name, parent) VALUES("Category 3", "0");
INSERT INTO categories (name, parent) VALUES("Category 4", "0");
INSERT INTO categories (name, parent) VALUES("Subcategory 1", "2");
INSERT INTO categories (name, parent) VALUES("Subcategory 2", "2");
INSERT INTO categories (name, parent) VALUES("Subcategory 3", "5");
INSERT INTO categories (name, parent) VALUES("Subcategory 4", "9");
INSERT INTO categories (name, parent) VALUES("Category 5", "0");


As you can see, the table layout is quite simple.. here's an example of how it works (simplified a bit):

Code:
|----|---------------|--------|
| id | name          | parent |
|----|---------------|--------|
|  1 | Category 1    | 0      |
|  2 | Subcategory 1 | 1      |
|  3 | Subcategory 2 | 1      |
|  4 | Subcategory 3 | 2      |
|----|---------------|--------|



According to the simplified example above, the output would be:

Code:
Category 1
-- Subcategory 1
---- Subcategory 3
-- Subcategory 2


All right.. let's go on to the nasty part.. the actual code.. if you've got any better way to this, or have any suggestions for the already existing code, feel free to e-mail it to me at lindset@webpixels.net, or just post it in this thread..

PHP Code:
<?php

mysql_connect
('localhost''username''password') or die(mysql_error());
mysql_select_db('test_tree') or die(mysql_error());

function 
get_tree() {
    global 
$current_level;
    
    
$result mysql_query('SELECT id, name, parent
                           FROM categories
                           ORDER BY name'
) or die(mysql_error());
    
    while (
$row mysql_fetch_array($result)) {
        
// create an array containing _all_ of the cateogries
        
$temp_tree[] = array(
                              
'id'     => $row['id'],
                              
'name'   => $row['name'],
                              
'parent' => $row['parent']
                            );
    }
    
    foreach (
$temp_tree as $key => $value) {
        if (!
$value['parent']) {
            
// all right, it's a root category
            
$current_level 0;
            
            
$new_tree[] = array(
                                
'id'     => $value['id'],
                                
'name'   => $value['name'],
                                
'parent' => $value['parent'],
                                
'level'  => $current_level
                               
);
            
            if (
$branch get_leafs($temp_tree$value['id'])) {
                
// merge the new array with the old array
                
$new_tree array_merge($new_tree$branch);
            }
        }
    }
    
    return isset(
$new_tree) ? $new_tree false;
}

function 
get_leafs($temp_tree$id) {
    global 
$current_level;
    
    
$current_level++;
    
    foreach (
$temp_tree as $key => $value) {
        if (
$value['parent'] == $id) {
            
// all right, the parent id is a match
            
$new_tree[] = array(
                                
'id'     => $value['id'],
                                
'name'   => $value['name'],
                                
'parent' => $value['parent'],
                                
'level'  => $current_level
                               
);
            
            if (
$branch get_leafs($temp_tree$value['id'])) {
                
// merge the new array with the old array
                
$new_tree array_merge($new_tree$branch);
            }
            
            
$current_level--;
        }
    }
    
    return isset(
$new_tree) ? $new_tree false;
}

foreach (
get_tree() as $value) {
    echo 
str_repeat("--"$value['level']) . $value['name'] . '<br>';
}

?>


Ok.. to help you visualize the array in your head, here's an example of the structure after processing:

Code:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Category 1
            [parent] => 0
            [level] => 0
        )

    [1] => Array
        (
            [id] => 2
            [name] => Category 2
            [parent] => 0
            [level] => 0
        )

    [2] => Array
        (
            [id] => 5
            [name] => Subcategory 1
            [parent] => 2
            [level] => 1
        )

    [3] => Array
        (
            [id] => 7
            [name] => Subcategory 3
            [parent] => 5
            [level] => 2
        )

    [4] => Array
        (
            [id] => 6
            [name] => Subcategory 2
            [parent] => 2
            [level] => 1
        )

    [5] => Array
        (
            [id] => 3
            [name] => Category 3
            [parent] => 0
            [level] => 0
        )

    [6] => Array
        (
            [id] => 4
            [name] => Category 4
            [parent] => 0
            [level] => 0
        )

    [7] => Array
        (
            [id] => 9
            [name] => Category 5
            [parent] => 0
            [level] => 0
        )

    [8] => Array
        (
            [id] => 8
            [name] => Subcategory 4
            [parent] => 9
            [level] => 1
        )

)


To display it correctly, all you have to do is iterate through the array.. like you see at the end of the example.. here's the final output of the php code above:

Code:
Category 1
Category 2
--Subcategory 1
----Subcategory 3
--Subcategory 2
Category 3
Category 4
Category 5
--Subcategory 4


What do you think? I haven't commented the code heavily, so, if you're having difficulties understanding a part of the code, feel free to ask here, and I'll try to answer..
__________________
Best Regards,
Håvard Lindset

Last edited by Lindset : November 5th, 2002 at 04:26 PM.

Reply With Quote
  #2  
Old November 5th, 2002, 03:14 PM
Taelo Taelo is offline
5B's
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Oct 2002
Location: PC, FL
Posts: 366 Taelo User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 30 m 59 sec
Reputation Power: 7
you forgot something :/

Code:
CREATE TABLE categories (
  C_ID mediumint(8) unsigned NOT NULL auto_increment,
  C_TITLE varchar(100) NOT NULL default '',
  C_ORDER mediumint(8) unsigned NOT NULL default '0',
  C_ACTIVE enum('Y','N') NOT NULL default 'Y',
  C_PARENT tinyint(11) unsigned NOT NULL default '0',
  PRIMARY KEY  (C_ID)
) TYPE=MyISAM;



Key parts are Order, and Status

Reply With Quote
  #3  
Old November 5th, 2002, 05:49 PM
Lindset Lindset is offline
weirdomoderator
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2002
Location: Alta, Norway
Posts: 370 Lindset User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 7
Send a message via ICQ to Lindset Send a message via AIM to Lindset
Quote:
Originally posted by Taelo
you forgot something :/

Code:
CREATE TABLE categories (
  C_ID mediumint(8) unsigned NOT NULL auto_increment,
  C_TITLE varchar(100) NOT NULL default '',
  C_ORDER mediumint(8) unsigned NOT NULL default '0',
  C_ACTIVE enum('Y','N') NOT NULL default 'Y',
  C_PARENT tinyint(11) unsigned NOT NULL default '0',
  PRIMARY KEY  (C_ID)
) TYPE=MyISAM;



Key parts are Order, and Status


I'm not sure what you mean..

Reply With Quote
  #4  
Old November 5th, 2002, 09:05 PM
Taelo Taelo is offline
5B's
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Oct 2002
Location: PC, FL
Posts: 366 Taelo User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 30 m 59 sec
Reputation Power: 7
well,...how are you going order your categories? by Name? that can get confusing for users if you keep adding categories. So I have an Order Field, which I store my order in.

The Status is for the admin f he wishes to turn off a category without deleting anything asociated to it

Name Order Status
Cat 1 1 Y
Cat 2 2 Y
Cat 5 3 N
Cat 123 4 Y



In this case,....this would print,...Cat 1, 2 and 123 but not 5

Make sense?

-- Jason

Reply With Quote
  #5  
Old November 6th, 2002, 12:34 AM
Lindset Lindset is offline
weirdomoderator
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2002
Location: Alta, Norway
Posts: 370 Lindset User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 7
Send a message via ICQ to Lindset Send a message via AIM to Lindset
Quote:
Originally posted by Taelo
well,...how are you going order your categories? by Name? that can get confusing for users if you keep adding categories. So I have an Order Field, which I store my order in.

The Status is for the admin f he wishes to turn off a category without deleting anything asociated to it

Name Order Status
Cat 1 1 Y
Cat 2 2 Y
Cat 5 3 N
Cat 123 4 Y



In this case,....this would print,...Cat 1, 2 and 123 but not 5

Make sense?

-- Jason


Ok, but I didn't want to make the example more complicated than it already is..

Reply With Quote
  #6  
Old November 6th, 2002, 09:06 AM
Taelo Taelo is offline
5B's
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Oct 2002
Location: PC, FL
Posts: 366 Taelo User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 30 m 59 sec
Reputation Power: 7
not complicated at all

PHP Code:
 mysql_query("SELECT * FROM categories WHERE C_ID = '{$_GET['C_ID']}' AND C_STATUS = 'Y' ORDER BY C_ORDER"); 



blammo,...there ya go

Reply With Quote
  #7  
Old November 6th, 2002, 09:25 AM
Lindset Lindset is offline
weirdomoderator
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2002
Location: Alta, Norway
Posts: 370 Lindset User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 7
Send a message via ICQ to Lindset Send a message via AIM to Lindset
thanks but the example is simply supposed to show how to display something in a tree structure (not necessarily categories), that's why I didn't want to make it too specific for example categories.. when showing examples, you want to simplify it so it's easier for the audience to understand..

Reply With Quote
  #8  
Old November 6th, 2002, 02:35 PM
Taelo Taelo is offline
5B's
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Oct 2002
Location: PC, FL
Posts: 366 Taelo User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 30 m 59 sec
Reputation Power: 7
easy is not always best

Reply With Quote
  #9  
Old March 28th, 2003, 05:32 PM
donovanh donovanh is offline
Junior Member
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Mar 2003
Posts: 1 donovanh User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
I'm working on a site to display a tree view of registered users. So far i can only work out how to display the first level.. to see what i mean, its on this page:

URL

The tables include these fields currently being used:
------------------------------------------------
| id | Firstname | Surname | Sponsor |
------------------------------------------------
| 1 | Don | H | 1 |
| 2 | Number 2 | 2 | 1 |
etc
------------------------------------------------

Where you have id and parent, i have id and sponsor. I'd like to use the script here, but when i implement it and change the names i get this warning message:

----------------
Warning: Invalid argument supplied for foreach()
----------------

The echo command is not writing anything to the page, and the warning message identifies the final 'foreach' at the end of the code. Any idea what could be causing this?

Thanks,

Don

Reply With Quote
  #10  
Old March 30th, 2003, 01:41 PM
FrankieShakes FrankieShakes is offline
Frank The Tank!
Dev Articles Beginner (1000 - 1499 posts)
 
Join Date: Jun 2002
Location: Toronto, Canada
Posts: 1,246 FrankieShakes User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 8
Send a message via ICQ to FrankieShakes Send a message via MSN to FrankieShakes
Don,

Would it be possible to post the code you're using? If might give us a better idea of what could be going wrong....

How are you structuring your foreach loop?
__________________
____________________________________________
Developer Shed Weekly Writer | DevArticles Forum Moderator
Build Your Own KlipFolio Klip With PHP
FrankManno.com - Under Construction
Design Interactive Group - Under Construction

Reply With Quote
  #11  
Old March 31st, 2003, 08:16 AM
zigote zigote is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Aug 2002
Location: Atlanta GA
Posts: 73 zigote User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 55 m 11 sec
Reputation Power: 7
How would you link a Subcategory, to it's right article that's in another database, Name Articles ?

Here's what I'm trying to do.

Add Topics Titles to the database.
Then add topics that would be listed as subcategories,

example:
Topic 1 PHP
--Articles about php --> URL is: topics.php?sub=ID#
--Articles about functions --> URL is: topics.php?sub=ID#

Topic 2 ASP
--Articles about php --> URL is: topics.php?sub=ID#
--Scripts --> URL is: topics.php?sub=ID#

The URL [?Id=ID#] would then list all articles of that subcategory.

I guess I'm trying to relate subTopics ID to the related Article ID.
I wanted to post a TopicTitle, Then a TopicSub, So, The TopicSub URL would pull all Articles that where related to that TopicSub.

I'm kind-0f , If you can tell.

Reply With Quote
Reply

Viewing: Dev Articles Community ForumsProgrammingGeneral Programming Help > Quick Example: How to show something hierarchically (tree structure)


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump