无限极 二维数组层级关系

 1 private function getArea(){
 2     $post_data = array();
 3     $result = $this->send_post('http://114.115.140.125:8051/?msgid=121&authkey=webuser&accountid='.$_SESSION['id'].'&projectid='.$_SESSION['projectid'].'',$post_data);
 4     $volist = json_decode($result,true);
 5     
 6     // 这一段应该是很通俗的,就是构建一个新的数组,新数组的key值是自己的主键id值进行完这一步之后  这步很重要
 7     $items = array();
 8     foreach($volist['regions'] as $v){
 9         $items[$v['id']] = $v;
10     }
11    
12   13     
14 
15     
16     # 第一步先简化数组 只要直接想要的几个字段   我这里需要 不需要的可以不用
17     $newData = array();
18     foreach($items as $ke=>$it){
19         $newData[$ke]['id'] = $it['id'];
20         $newData[$ke]['text'] = $it['name'];
21         $newData[$ke]['parentid'] = $it['parentid'];
22         $newData[$ke]['projectid'] = $it['projectid'];
23         $newData[$ke]['projectname'] = $it['projectname'];
24     }
25 
26     # 第二步 
27     # 先找到这个新数组中有没有这个key 如果没有 
28     $tree = array();
29     foreach($newData as $k => $item){
30         // 其实这里 "$newData[$item['parentid']]" 就是newData的下标,上面已经把每条信息的 id改成了自己的key  因为id= parentid
31         // 找到原数组 中上下关系字段 如果是0 肯定是false 则就是顶级
32         if(isset($newData[$item['parentid']])){
33             $newData[$item['parentid']]['nodes'][] = &$newData[$k];  
34             // 若不为真 把这条数据拿到key等于这条数据的parentid的下面 自定义下标名称并且多加一个"[]"万一这个id下面的子类有多个
35         }else{
36             $tree[] = &$newData[$k];  // 顶级
37         }
38     }
39     return $tree;
40 }


// 结果 我这里数据有点少 但是基本上看的清楚 如果还有 子类 孙子类 都会追加到相应的父类后面
 1 
 2 array(3) {
 3   [0] => array(6) {
 4     ["id"] => int(49)
 5     ["text"] => string(12) "车身车间"
 6     ["parentid"] => int(0)
 7     ["projectid"] => int(16)
 8     ["projectname"] => string(12) "南京大通"
 9     ["nodes"] => array(1) {
10       [0] => array(5) {
11         ["id"] => int(75)
12         ["text"] => string(3) "456"
13         ["parentid"] => int(49)
14         ["projectid"] => int(16)
15         ["projectname"] => string(12) "南京大通"
16       }
17     }
18   }
19   [1] => array(6) {
20     ["id"] => int(50)
21     ["text"] => string(12) "冲压车间"
22     ["parentid"] => int(0)
23     ["projectid"] => int(16)
24     ["projectname"] => string(12) "南京大通"
25     ["nodes"] => array(1) {
26       [0] => array(5) {
27         ["id"] => int(78)
28         ["text"] => string(3) "666"
29         ["parentid"] => int(50)
30         ["projectid"] => int(16)
31         ["projectname"] => string(12) "南京大通"
32       }
33     }
34   }
35   [2] => array(5) {
36     ["id"] => int(82)
37     ["text"] => string(12) "总装车间"
38     ["parentid"] => int(0)
39     ["projectid"] => int(16)
40     ["projectname"] => string(12) "南京大通"
41   }
42 }

猜你喜欢

转载自www.cnblogs.com/G921123/p/10086613.html