SitePoint Sponsor |
|
User Tag List
Results 1 to 2 of 2
-
Apr 1, 2009, 00:10 #1
- Join Date
- Oct 2008
- Posts
- 295
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Problem outputting tree hierarchy.
Hi,
So here is the deal. I get results from database in array which is something like this:
Code:Array ( [0] => Array ( [feature_name] => test parent 1 [feature_id] => 883 [parent_feature_id] => 0 ) [1] => Array ( [feature_name] => child 1 [feature_id] => 884 [parent_feature_id] => 883 ) [2] => Array ( [feature_name] => child 1-2 [feature_id] => 885 [parent_feature_id] => 883 ) [3] => Array ( [feature_name] => test parent 2 [feature_id] => 886 [parent_feature_id] => 0 ) [4] => Array ( [feature_name] => child 2-1 [feature_id] => 887 [parent_feature_id] => 886 ) [5] => Array ( [feature_name] => child 2-2 [feature_id] => 888 [parent_feature_id] => 886 ) [6] => Array ( [feature_name] => test feature without children [feature_id] => 889 [parent_feature_id] => 0 ) [7] => Array ( [feature_name] => grandchild-1-1 [feature_id] => 890 [parent_feature_id] => 884 ) [8] => Array ( [feature_name] => grandchild-1-2 [feature_id] => 891 [parent_feature_id] => 884 ) )
Code:o test parent 1 - child 1 * grandchild 1-1 * grandchild 1-2 - child 1-2 o test parent 2 - child 2-1 - child 2-2 o testi feature without children
-TeNDoLLA
-
Apr 1, 2009, 01:00 #2
- Join Date
- Jan 2007
- Location
- Romania
- Posts
- 203
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
The following code should work.
PHP Code:<?php
$source = array(
array('id' => 1, 'feature' => 'f1', 'parent_feature_id' => 0),
array('id' => 2, 'feature' => 'f1.1', 'parent_feature_id' => 1),
array('id' => 3, 'feature' => 'f1.1.1', 'parent_feature_id' => 2),
array('id' => 4, 'feature' => 'f2', 'parent_feature_id' => 0),
array('id' => 5, 'feature' => 'f1.1.2', 'parent_feature_id' => 2),
);
$map = array();
for ($i = 0, $n = count($source); $i < $n; $i++) {
$source[$i]['children'] = array();
$map[$source[$i]['id']] = $i;
}
$tree = array();
for ($i = 0; $i < $n; $i++) {
$node = $source[$i];
if (0 == $node['parent_feature_id']) {
$tree[] = &$source[$i];
}
else {
$source[$map[$node['parent_feature_id']]]['children'][] = &$source[$i];
}
}
var_dump($tree); // this is your tree
?>
Bookmarks