|
Posted by Zilla on 12/15/05 15:57
I don't want to get into the discussion the other guys are having.
Instead I have made a solution which gives you exactly what you
requested. Nothing more, nothing less. Here goes:
<?php
//Connect to mysql. Remember to change host, user, pass, db and tbl_name.
$link = mysql_connect("mysql_host", "mysql_user", "mysql_pass");
mysql_select_db("mysql_db");
$query = "SELECT * FROM tbl_name";
$result = mysql_query($query);
$i = 0;
//Store ids, uris, names and parent ids in arrays for later use.
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$ids[$i] = $row['id'];
$uris[$i] = $row['uri'];
$names[$i] = $row['name'];
$parent_ids[$i] = $row['parent_id'];
$i++;
}
//Make pairs of ids and parent ids.
foreach($ids as $key => $value) {
$array[] = $parent_ids[$key] . " " . $value;
}
//Make flat tree structure.
function make_flat_tree($array) {
$test = 0;
foreach($array as $key => $value) {
$used = 0;
foreach($array as $key2 => $value2){
if($key != $key2) {
$explode = explode(" ", $value);
$explode2 = explode(" ", $value2);
$count = count($explode) - 1;
$last = count($explode2) - 1;
$count2 = count($explode2) - 2;
if($explode[$count] == $explode2[$count2]) {
$flattree[] = $value . " " . $explode2[$last];
$test = 1;
$used = 1;
unset($array[$key2]);
}
}
}
if($used == 1) {
unset($array[$key]);
}
}
if(count($array) > 0) {
foreach($array as $value) {
$flattree[] = $value;
}
}
if($test == 1) {
$flattree = make_flat_tree($flattree);
}
return $flattree;
}
$flattree = make_flat_tree($array);
//Remove leading zeros.
foreach($flattree as $value) {
$flattree2[] = substr($value, 2);
}
//Build tree structure with only ids.
function build_tree($array) {
foreach($array as $value) {
$structure = "\$tree";
$explode = explode(" ", $value);
foreach($explode as $value2) {
$structure = $structure . "[" . $value2 . "]";
}
$structure = $structure . " = 0;";
eval($structure);
}
return $tree;
}
$tree = build_tree($flattree2);
ksort($tree);
//Make arrays containing forum details.
foreach($ids as $key => $value) {
$forums[] = array("id" => $ids[$key], "uri" => $uris[$key],
"name" => $names[$key], "parent_id" => $parent_ids[$key] , "sub_forums"
=> array());
}
//Build final tree structure by joining information from $tree and $forums.
function build_full_tree($tree, $forums) {
foreach($tree as $key => $value) {
if(is_array($value)) {
foreach($forums as $value2) {
if($value2['id'] == $key) {
$value2['sub_forums'] =
build_full_tree($value, $forums);
$tree2[] = $value2;
}
}
} else {
foreach($forums as $value3) {
if($value3['id'] == $key) {
$tree2[] = $value3;
}
}
}
}
return $tree2;
}
$tree2 = build_full_tree($tree, $forums);
?>
$tree2 now contains exactly the array you provided.
Zilla.
Navigation:
[Reply to this message]
|