Answer the question
In order to leave comments, you need to log in
Category tree processing?
Hello, there is a table with categories (its structure is in the picture).
I managed to build the tree itself based on id and parent_id:
function getCats($res){
$levels = array();
$tree = array();
$cur = array();
foreach($res as $rows){
$cur = &$levels[$rows['id']];
$cur['parent_id'] = $rows['parent_id'];
$cur['title'] = $rows['title'];
if($rows['parent_id'] == 0){
$tree[$rows['id']] = &$cur;
}
else{
$levels[$rows['parent_id']]['children'][$rows['id']] = &$cur;
}
}
return $tree;
}
function getTree($arr, $nl = 1, $nr = 0){
$out = '';
$out .= '<ul>';
foreach($arr as $k=>$v){
$out .= '<li>'.$v['title'].' - id : '.$k.' - pid : '.$v['parent_id']."</li><li>nl : ".$nl." - nr : ".$nr."</li>";
if(!empty($v['children'])){
$out .= getTree($v['children'], $nl, $nr);
}
}
$out .= '</ul>';
return $out;
}
$cats = getCats($array);
echo getTree($cats);
Slightly corrected functions found on the Internet. Answer the question
In order to leave comments, you need to log in
In this example, 2 tree storage models were mixed in a relational database:
1) id-paraent_id - a list of adjacent vertices ( Adjacency List )
2) NSLeft and NSRight - nested sets ( Nested Set )
You can read it here: " Hierarchical structures yes ... ".
The point here is that the Nested Set is less error tolerant than the Adjacency List. So if " NSLeft and NSRight ... are empty ", then the tree falls apart. Therefore, "reproducing their values for each of the categories" will not work. To do this, you need to restore the tree using data from the Adjacency List of the tree. After repairing the tree, the selection from the Nested Set can be made by generally accepted queries (read the link above).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question