JavaScript-How to create a three-level linkage menu tree based on the following array? (Consider performance)

Source: Internet
Author: User
First-level ID is negative, parentid is empty, level two parentid equals first level ID, level three parentid equals level two ID
[{"Name": "Guangdong", "Id":-1, "ParentID": null},
{"Name": "Hubei", "Id":-2, "ParentID": null},
{"Name": "Guangzhou", "Id": +, "ParentID":-1},
{"Name": "Wuhan", "Id": +, "ParentID":-2},
{"Name": "Shenzhen", "Id": "ParentID":-1},
{"Name": "White Cloud", "Id": 741, "ParentID": 44}]

Reply content:

First-level ID is negative, parentid is empty, level two parentid equals first level ID, level three parentid equals level two ID
[{"Name": "Guangdong", "Id":-1, "ParentID": null},
{"Name": "Hubei", "Id":-2, "ParentID": null},
{"Name": "Guangzhou", "Id": +, "ParentID":-1},
{"Name": "Wuhan", "Id": +, "ParentID":-2},
{"Name": "Shenzhen", "Id": "ParentID":-1},
{"Name": "White Cloud", "Id": 741, "ParentID": 44}]

Effect

It's a bit ugly, but it's not limited by the sort of array (not necessarily descending by progression), nor is it limited to level 3.

In fact, this is a recursive relationship, paste the code in my project:

/** * Gets the tree's drop-down array of trees * @param string $model model name * @param int $m Number of point characters * @param string $pid Parent ID * @param array Field name arrays */function Dropdown_tree ($model, $m =0, $pid =0, $field =array (' id ', ' sortname ', ' ParentID ') {$model = $model. " _model "; $this->_ci->load->model ($model); $class _arr= $this->_ci-> $model->all (); $return _arr=array (); $this->dropdown_array ($m, $pid, $class _arr, $return _arr, $field); return $return _arr; }/** * Iterate through the array and modify its style. */function Dropdown_array ($m, $pid, $class _arr,& $return _arr, $field) {$n = Str_pad (", $m, '-', str_pad_right); $n = Str_replace ("-", "" ", $n); foreach ($class _arr as $item) {if ($item ["$field [2]"]== $pid) {$return _arr[$item ["$field [0]"]]= $n. " |--". $item [" $field [1] "]; $this->dropdown_array ($m +1, $item ["$field [0]"], $class _arr, $return _arr, $field); } } }

Go straight to an infinite class of code.

Javascript version

var districts = [{"Name": "Guangdong", "id": 1, "ParentID": 0}, {"name": "Hubei", "id": 2, "ParentID": 0}, {"N Ame ":" Guangzhou "," id ": 3," ParentID ": 1}, {" Name ":" Wuhan "," id ": 4," ParentID ": 2}, {" Name ":" Shenzhen "," id ": 5," Parent ID ": 0}, {" Name ":" White Cloud "," id ": 6," ParentID ": 3}, {" Name ":" Jiangxia "," Id ": 7," ParentID ": 4}, {" Name ":" King Wan        Path "," Id ": 8," ParentID ": 6}];        function Arraytotree (parentid) {var temp = [];                    For (var index in districts) {if (Districts[index].parentid = = ParentID) {Temp.push ({ Data:districts[index], Children:arraytotree (Districts[index].            ID)});    }} return temp;        } function Outputtree (items, depth) {var str = ';  For (var index in items) {/* repeat () attribute belongs to ECMAScript (ES6) specification */str + = '--'. Repeat (depth) + Items[index].data.name + '
'; if (items[index].children.length) {str + = Outputtree (items[index].children, depth + 1); }} return str; } var result = Outputtree (arraytotree (0), 0); document.write (result);

The final output results are as follows:

广东- - 广州- - - - 白云- - - - - - 景云路湖北- - 武汉- - - - 江夏深圳

PS: Separators can be customized. Ask Daniel to help optimize: arrayToTree() ^_^

PHP version

Previously written, please poke here directly, too lazy to copy the _^_.

Very concerned about the performance of this because the order of magnitude can not be considered without the 3-level linkage, processing, and then enter the following option on the line.
Home
-Home
--Home
Home

is based on the ID to find the classification, direct JQ judgment record is good

Do not invite self-answer, (consider the performance) private thinking at the root of the data is the most effective direct, to a database version.
Build a Table statement

create table TP_CITY(  Id      NUMBER ,  name    VARCHAR2(255),  parentId    NUMBER);insert into tp_city values(-1,'广东', null);insert into tp_city values(-2,'湖北', null);insert into tp_city values(44,'广州', -1);insert into tp_city values(58,'武汉', -2);insert into tp_city values(12,'深圳', -1);insert into tp_city values(741,'白云', 44);

For example, using Oracle's hierarchical query

select lpad(' ', (level-1)*2, ' ')||name namefrom tp_citystart with id<0 connect by parentId=prior Id;

The returned results are as follows:

We can also write this:

select sys_connect_by_path(name, '-') pathfrom tp_citystart with id<0 connect by parentId=prior id;

The return result is:

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.