I
I
iwebber2014-02-07 16:01:13
PHP
iwebber, 2014-02-07 16:01:13

Category tree processing?

Hello, there is a table with categories (its structure is in the picture).
2a212ffc46a44b310424205d10a1ee7c.png
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.
The NSLeft and NSRight columns in the table are filled in correctly, but let's pretend they are empty.
I can't just reproduce their values ​​for each of the categories .
If someone can help I would be extremely grateful.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Sundukov, 2014-02-07
@alekciy

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).

I
iwebber, 2014-02-08
@iwebber

@alekciy , it was the NSLeft / NSRight values ​​on the site that broke.
Probably, initially I did not formulate the question precisely, but I also want to "restore the tree using the data from the Adjacency List of the tree.", which does not work out.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question