当前位置:网站首页>PHP implementation of infinite classification tree (recursion and Optimization)
PHP implementation of infinite classification tree (recursion and Optimization)
2022-06-12 17:49:00 【Wind broken peak】
One 、 Requirements describe
Interface function description :
Query the complete domestic administrative division information , All provinces 、 All prefecture level cities under the province 、 All districts and counties under prefecture level cities , All data is returned only id、admincode、name、simple_name、lng、lat Six fields .
Two 、 Background Overview
Target table structure :
CREATE TABLE `lbs_district` (
`id` char(19) NOT NULL DEFAULT '0' COMMENT '19 position ID',
`parent_id` char(19) NOT NULL DEFAULT '0' COMMENT ' Of a higher administrative division 19 position ID',
`name` varchar(100) NOT NULL DEFAULT '' COMMENT ' name ',
`level` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT ' type :1: Countries and regions ,2: Province ,3: Prefecture level cities ,4: District and county ,5: The street ,6: Township 、 other ,7: Noodle business district ,8: Point business district ',
`level_name` varchar(20) NOT NULL DEFAULT '' COMMENT ' Type the name :1:country,2:province,3:city,4:county,5:town,6:town,7:business,8:business',
`lng` float(10,6) NOT NULL DEFAULT '0.000000' COMMENT ' Center point longitude, Longitude coordinates ',
`lat` float(10,6) NOT NULL DEFAULT '0.000000' COMMENT ' Center point latitude, Latitude coordinates ',
`admincode` char(6) NOT NULL DEFAULT '0' COMMENT ' Standard national administrative divisions 6 Bit code ',
`is_foreign` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT ' type :1: Mainland China, Hong Kong and Macao ,2: Taiwan and abroad ',
`deleted` tinyint(1) NOT NULL DEFAULT '0' COMMENT ' Identify deletion status :0: Don't delete ,1: Delete ',
`deltime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT ' Delete time ',
`ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ' Creation time ',
`mtime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT ' Update time ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=' Administrative division and business district information table ';
After obtaining the administrative division data from the database , Output Province in tree structure 、 City 、 District and county level administrative division data .
3、 ... and 、 Code implementation
Consider that the data obtained from the library is 3000 multiple , It basically includes the data of the whole country , So it is also possible to consider recursion .
<?php
/**
* <p>
* Interface function description : Query the complete domestic administrative division information
* </p>
*
* <p>
* Description of data structure of interface output : Output data to JSON Array form returns , example :
* <blockquote><pre>
* [{
* "id":"8008611000000000000",
* "parent_id":"8008600000000000000",
* "admincode":"110000",
* "name":" The Beijing municipal ",
* "simple_name":" Beijing ",
* "lng":"116.405289",
* "lat":"39.904987"
* },
* {
* "id":"8008612010500000000",
* "parent_id":"8008600000000000000",
* "admincode":"120105",
* "name":" Hebei Province ",
* "simple_name":" hebei ",
* "lng":"117.201569",
* "lat":"39.156631"
* }]
* <blockquote><pre>
* </p>
*
* @author bingqing5
* @date 2022/05/16
*/
header('Content-type: application/json');
require_once 'district_common.php';
/**
* Generate tree structure data
* @param $items Processing target data stored as an array
* @param $parentId Parent node ID
* @return array
*/
function generateTree($items , $parentId)
{
// Initializing an array , Used to store output data
$tree = array();
/* Traversal array , Recursive processing of data */
foreach($items as $k => $v)
{
/* Judge the status of the current node parentId Whether it is the same as the parameter ?
* If the same , Recursion down the same parent node . further
* Judge whether the child nodes of the current node are not empty , If you don't
* It's empty , Put the current node into the current parent node's children in
*/
if($v['parent_id'] == $parentId)
{
$set = generateTree($items , $v['id']);
if (!empty($set))
{
$v['children'] = generateTree($items , $v['id']);
}
$tree[] = $v;
}
}
return $tree;
}
$sql = "
SELECT
ld.id,
ld.parent_id,
ld.admincode,
ld.name,
lde.simple_name,
ld.lng,
ld.lat,
ld.level
FROM
lbs_district ld
LEFT JOIN lbs_district_extends lde ON ld.id = lde.lbs_district_id
WHERE
ld.is_foreign = 1
AND ld.level IN (2,3,4)
ORDER BY ld.id ASC";
$return = $db->getAll($sql);
// It is required to obtain the information of domestic province 、 City 、 The tree structure of district and county administrative divisions , Therefore, the root node is the administrative division of China ID
$treeRes = generateTree($return, '8008600000000000000');
echo json_encode($treeRes);;
$db->close();
?>The above code is due to the internal project environment of the company , It uses PHP5, The recursive part of the code uses PHP7 It can be written like this :
function generateTree($items , $parentId)
{
$tree = [];
foreach($items as $k => $v)
{
if($v['parent_id'] == $parentId)
{
if (!empty(generateTree($items , $v['id'])))
{
$v['childs'] = generateTree($items , $v['id']);
}
$tree[] = $v;
}
}
return $tree;
}Words ,PHP It's really a pit , Author use PHP7 The writing method of "run on the line" , Always reporting mistakes . Because the author's job is Java Development , Yes PHP That's all Greek , It was also undertaken temporarily at the request of the team leader PHP Development tasks , When writing code, it is inevitable to always bring Java Grammar habits of ...
Four 、 Optimize
After submitting the code , Online testing , The result is shown in Fig. :

Obviously , The interface needs to get the data 20s, This is an unacceptable thing . after , On this basis, colleagues completed the optimization , The code is as follows :
<?php
/**
* <p>
* Interface function description : Query the complete domestic administrative division information
* </p>
*
* <p>
* Description of data structure of interface output : Output data to JSON Array form returns , example :
* <blockquote><pre>
* [{
* "id":"8008611000000000000",
* "parent_id":"8008600000000000000",
* "admincode":"110000",
* "name":" The Beijing municipal ",
* "simple_name":" Beijing ",
* "lng":"116.405289",
* "lat":"39.904987"
* },
* {
* "id":"8008612010500000000",
* "parent_id":"8008600000000000000",
* "admincode":"120105",
* "name":" Hebei Province ",
* "simple_name":" hebei ",
* "lng":"117.201569",
* "lat":"39.156631"
* }]
* <blockquote><pre>
* </p>
*
* @author bingqing5
* @date 2022/05/16
*/
header('Content-type: application/json');
require_once 'district_common.php';
/**
* Generate tree structure data
* @param $items Processing target data stored as an array
* @param $parentId Parent node ID
* @return array
*/
function generateTree($items , $parentId) {
// Initializing an array , Used to store output data
$tree = array();
/* Traversal array , Recursive processing of data */
foreach($items as $k => $v) {
/* Judge the status of the current node parentId Whether it is the same as the parameter ?
* If the same , Recursion down the same parent node . further
* Judge whether the child nodes of the current node are not empty , If you don't
* It's empty , Put the current node into the current parent node's children in
*/
if(isset($v['parent_id']) && $v['parent_id'] == $parentId) {
if($v['level']!=4){// Only provincial and prefecture level cities have child nodes
$set = generateTree($items , $v['id']);
if (!empty($set)) {
$v['children'] = generateTree($items , $v['id']);
}
// $v['children'] = generateTree($items , $v['id']);
}
unset($v['parent_id']);// Fewer output fields , Increase interface speed
$tree[] = $v;
}
}
return $tree;
}
// Too much data , Only some basic data is output , Disassociate , Will it be very slow
/*
$sql = "
SELECT
ld.id,
ld.parent_id,
ld.admincode,
ld.name,
lde.simple_name,
ld.lng,
ld.lat,
ld.level
FROM
lbs_district ld
LEFT JOIN lbs_district_extends lde ON ld.id = lde.lbs_district_id
WHERE
ld.is_foreign = 1
AND ld.level IN (2,3,4)
ORDER BY ld.id ASC";
*/
$sql = "
SELECT
ld.id,
ld.parent_id,
ld.name,
ld.lng,
ld.lat,
ld.level
FROM
lbs_district ld
WHERE
ld.is_foreign = 1
AND ld.level IN (2,3,4)
ORDER BY ld.id ASC";
$return = $db->getAll($sql);
// It is required to obtain the information of domestic province 、 City 、 The tree structure of district and county administrative divisions , Therefore, the root node is the administrative division of China ID
$treeRes = generateTree($return, '8008600000000000000');
echo json_encode($treeRes);;
$db->close();
?>The response speed of the optimized interface is greatly improved , Pictured :

边栏推荐
- 徽商期货公司开户可靠,交易安全吗?
- Vulnhub[DC3]
- Arm64 Stack backtrack
- 406. reconstruct the queue based on height
- Hangzhou AI developer meetup registration opens!
- How to change Golan back to the English version when it becomes the Chinese version
- Extreme Programming -- Practice of root cause analysis
- TensorFlow从网络读取数据
- Error record: illegalstateexception: optional int parameter 'XXXX' is
- The server time zone value ‘� й ��� ʱ ��‘ is unrecognized or represents more than one time zone. ......
猜你喜欢

Deep interest evolution network for click through rate prediction

Some introduction to FPC flexible circuit board design

利用小程序快速生成App,只需七步
![[csp]202012-2 optimal threshold for period end forecast](/img/40/9b59bd692bcfe05d16614cc6d55d1f.png)
[csp]202012-2 optimal threshold for period end forecast

用好IDE,研发效能提速100%

Cesium抛物线方程
Goframe gredis configuration management | comparison of configuration files and configuration methods

Hangzhou AI developer meetup registration opens!

Office application cannot start normally 0xc0000142

文章名字
随机推荐
Arm64棧回溯
Getting started with grpc swift
分辨率与行场同步信号的关系 场消隐
Codeforces Round #398 (Div. 2) D. Cartons of milk
bug记录:更新数据库时报错:Data truncation: Incorrect datetime value:
TensorFlow从网络读取数据
赛程更新| 2022微软与英特尔黑客松大赛火热报名中
JDBC quick start tutorial
Flink 维表异步查询的实现以及问题排查
Sqlserver common statements and functions
Hangzhou AI developer meetup registration opens!
grpc-swift入门
论文《Deep Interest Evolution Network for Click-Through Rate Prediction》
Bug record: data truncation: incorrect datetime value:
Cesium parabolic equation
Alibaba cloud image station supports IPv6!
vant3+ts+pinia tab选项卡列表页面点击进详情,详情页返回tab高亮在原位置,刷新高亮默认在第一项
566. 重塑矩阵
Kali2022 installing Armitage
406. reconstruct the queue based on height