M
M
Miroslav Prikhodko2017-10-02 07:51:50
PHP
Miroslav Prikhodko, 2017-10-02 07:51:50

How to create a dropdown multilevel tree view?

The essence of the question is that we need a drop-down multi-level tree-like list that receives data from the database, there is already a code, with the only exception that the expansion is not configured, here is the result screen:
59d1c5bd3f959972380749.jpeg
here is the code

<?
include_once("bd.php");
header("Content-Type: text/html; charset=UTF-8");
//Выбираем данные из БД
$result=mysql_query("SELECT * FROM  table1");
//Если в базе данных есть записи, формируем массив
if   (mysql_num_rows($result) > 0){
    $cats = array();
//В цикле формируем массив разделов, ключом будет id родительской категории, а также массив разделов, ключом будет id категории
    while($cat =  mysql_fetch_assoc($result)){
        $cats_ID[$cat['uid']][] = $cat;
        $cats[$cat['pid']][$cat['uid']] =  $cat;
    }
}
function build_tree($cats,$parent_id,$only_parent = false){
    if(is_array($cats) and isset($cats[$parent_id])){
        $tree = '<ul>';
        if($only_parent==false){
            foreach($cats[$parent_id] as $cat){
                $tree .= '<li>'.$cat['name'].' #'.$cat['uid'];
                $tree .=  build_tree($cats,$cat['uid']);
                $tree .= '</li>';
            }
        }elseif(is_numeric($only_parent)){
            $cat = $cats[$parent_id][$only_parent];
            $tree .= '<li>'.$cat['name'].' #'.$cat['uid'];
            $tree .=  build_tree($cats,$cat['uid']);
            $tree .= '</li>';
        }
        $tree .= '</ul>';
    }
    else return null;
    return $tree;
}
echo build_tree($cats,0);
?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kalibrov, 2017-10-02
@rework

Here is a simple Jquery example - https://codepen.io/anikey99/pen/GJLdrZ

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question