针对无限极分类的整理

表结构为格式数据

id  name  p_id吉林省

 

形成的最终数据:

 

{

  "id":1,

  "name":"吉林省",

  "children":[

    {

      "id":2,
      "name":"长春市",

      children:[...]

    }  

  ]

}

 

从整体效率来讲,应该先从数据库查询,整理数据,然后通过程序,遍历形成最终格式数据,从而达到效率最大化。

 

1,数据操作:

https://www.cnblogs.com/duanrantao/p/9359137.html

 

2,程序操作:

https://www.jianshu.com/p/59aa4dfdcbd2

<?php
$arr = [
    [
      'id' => 2,
      'pid' => 1,
      'title' => '济南',
    ],
    [
        'id' => 3,
        'pid' => 1,
        'title' => '滨州',
    ],
    [
        'id' => 4,
        'pid' => 2,
        'title' => '历城区',
    ],
    [
        'id' => 5,
        'pid' => 2,
        'title' => '历下区',
    ],
    [
        'id' => 6,
        'pid' => 3,
        'title' => '沾化',
    ],
    [
        'id' => 7,
        'pid' => 3,
        'title' => '无棣',
    ],
    [
        'id' => 1,
        'pid' => 0,
        'title' => '山东',
    ],
    [
        'id' => 8,
        'pid' => 0,
        'title' => '北京',
    ],
    [
        'id' => 9,
        'pid' => 8,
        'title' => '朝阳区',
    ],
];
$res = [];

function get_attr($arr,$pid){
    $tree = array();                                //每次都声明一个新数组用来放子元素
    foreach($arr as $v){
        if($v['pid'] == $pid){                      //匹配子记录
            $v['child'] = get_attr($arr,$v['id']); //递归获取子记录
            if($v['child'] == null){
                unset($v['child']);             //如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选)
            }
            $tree[] = $v;                           //将记录存入新数组
        }
    }
    return $tree;                                  //返回新数组
}

$res = get_attr($arr, 0);

var_dump($res);

 

总结:此方法相当于先从根节点寻找,找到最下面的子集,然后从子集上unset,把这批找到的数据放到循环的节点上,然后逐级unset,一致递归到根节点。

 

posted on 2019-08-03 19:05  ziyi_ang  阅读(148)  评论(0编辑  收藏  举报

导航