Here im building a tree menu. A category is accessed by its id and its child displayed. my function works fine for two level menu but fails to generate level third. Third le
I see one problem with your solution. When you check for ID if($id == $record->id)
you will only match the current level in the tree. i.e. selecting Dell with id=2 will not match the first iteration so your function wil not traverse to next level.
You need to keep track of the path to your selected menu.
In your case. When you select Dell you will only se "Computer", am I right?
How about something like this:
...
function rederTreeById($records, $path) {
echo '<ul>';
foreach($records as $record) {
if(in_array($record->id, $path)) {
echo '<li>'.$record->title;
if(!empty($record->childs)) {
rederTreeById($record->childs, $path);
}
echo '</li>';
} else {
echo '<li>'.$record->title.'</li>';
}
}
echo '</ul>';
}
function getPath($id) {
$path = array();
$current=$id;
$path[] = 1
while(!is_null($categories[$current]->parent_id)) {
$current=$categories[$current]->parent_id
$path[] = $current;
}
return $path;
}
$selectedId = 1;
rederTreeById($rootCategories, getPath($selectedId));
...