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

来源:互联网 发布:qq空间网络音乐 编辑:程序博客网 时间:2024/04/30 16:03

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


 

?
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;
}


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