算法:将table标识的树形结构文本数据快速导入Mysql邻接表

问题:请根据题干描述你的算法,有以下树形结构的文本数据:


 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
部门A
     职员1
     职员2
     部门B
         职员3
         职员4
部门C
     职员5
     职员6
 
部门A
  职员1
  职员2
  部门B
   职员3
   职员4
部门C
  职员5
  职员6

它们用最常用的table符号标识其数据结构,请使用PHP计算出每条数据的路径、是否是叶子节点并导入一张邻接表。

 

 

 

答案:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//使用换行符号分割数组 
$arr = explode(PHP_EOL, PHP_EOL . $str);
//用来存储路径的数组 
$pathArr = array();
//储存结果的数组 
$reArr   = array();
//辅助变量 
$lastPos = $lastPosPre = 0;
  
foreach ($arr as $id => $v){
     //\t出现的次数 
     $lastPos = strrpos ($v, "\t");
     $lastPos = ($lastPos === FALSE)?0:$lastPos+1;
      
     //将路径压入数组 
     $pathArr[$lastPos] = $id;
      
     //计算出当前路径 
     $path = array_slice ($pathArr, 0, $lastPos);
      
     //计算父级id 
     $pid  = (int) isset ($pathArr[$lastPos - 1]) ? $pathArr[$lastPos - 1] : 0;
      
     //首次循环丢弃 
     if ($id == 0){continue;}
      
     //要写入数据库的数据 
     $reArr[$id] = array(
         'id'      => $id,
         'pid'     => $pid,
         'is_leaf' => 1,
         'path'    => '/' . implode('/', $path),
         'name'    => ltrim($v, "\t")
     );
      
     //是否叶子节点 
     if ($lastPos > $lastPosPre) {
         $reArr[$id-1]['is_leaf'] = 0;
     }
      
     //上一节循环中,\t出现的次数 
     $lastPosPre = $lastPos;
}
 
//使用换行符号分割数组
$arr = explode(PHP_EOL, PHP_EOL . $str);
//用来存储路径的数组
$pathArr = array();
//储存结果的数组
$reArr   = array();
//辅助变量
$lastPos = $lastPosPre = 0;
 
foreach ($arr as $id => $v){
  //\t出现的次数
  $lastPos = strrpos ($v, "\t");
  $lastPos = ($lastPos === FALSE)?0:$lastPos+1;
  
  //将路径压入数组
  $pathArr[$lastPos] = $id;
  
  //计算出当前路径
  $path = array_slice ($pathArr, 0, $lastPos);
  
  //计算父级id
  $pid  = (int) isset ($pathArr[$lastPos - 1]) ? $pathArr[$lastPos - 1] : 0;
  
  //首次循环丢弃
  if ($id == 0){continue;}
  
  //要写入数据库的数据
  $reArr[$id] = array(
   'id'      => $id,
   'pid'     => $pid,
   'is_leaf' => 1,
   'path'    => '/' . implode('/', $path),
   'name'    => ltrim($v, "\t")
  );
  
  //是否叶子节点
  if ($lastPos > $lastPosPre) {
   $reArr[$id-1]['is_leaf'] = 0;
  }
  
  //上一节循环中,\t出现的次数
  $lastPosPre = $lastPos;
}


 这份答案,可以导入无限深的树形结构数据。不过未经优化,等已有有时间再琢磨琢磨。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值