Skip to content | Skip to navigation
So, this is my simple looking problem:
Parsing a parent child tree into an unordered list in PHP 4. And no, PEAR is not an option.
I know of this solution, but it doesnt help me to get any further to my goal.
What I basically want to achieve is to:
a) retreive a tree-like structure (parent and child nodes) out of a SQL database table
b) output it as an unordered (nested) list, like it is shown in wast examples at Listamatic enabling me to style it the way I want it.
I've tried lots of hacks and own code, but right now, I'm stuck.
Somebody knows of a good solution for my problem, maybe some function library or PHP class letting you do this the easy way?
Any possible help is highly appreciated!
Thanks in advance,
cu, w0lf.
Fuck off the 30 seconds posting limit!
May 26, 2006 16:46 # 42831
WASABI *** (4) has a suggestion...
Somebody rated my posts, so now I can try to help :)
Ok, I assume your table is called table, and you have fields id and parent_id.
First method I'd do:
<?php
function tree($parent_id = 0)
{
$query = "select * from table where parent_id='$parent_id'";
$results = doquery($query); // We do the DB connect stuff, etc.
$return = array();
foreach ($results as $result) {
$item = array();
$item['id'] = $result['id'];
$item['children'] = tree($item['id']);
// Load other data you want
$return[] = $item;
}
return $return;
}
?>
Of course, this is completely procedural code, I'd do it with classes, objects, and all, but depending on your requirements, this might be useful.
Edit: added code tags.
:wq
This post was edited by WASABI on May 26, 2006.