当前位置:数据库 > SQLServer >>

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

 


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


 

部门A 
    职员1 
    职员2 
    部门B 
        职员3 
        职员4 
部门C 
    职员5 
    职员6 

部门A
 职员1
 职员2
 部门B
  职员3
  职员4
部门C
 职员5
 职员6

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

 

 

 

答案:

//使用换行符号分割数组  
$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;
}


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

补充:Web开发 , php ,
Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,